handler.get()
handler.get()
方法是对 [[Get]]
对象内部方法 的陷阱,被 属性访问器 等操作使用。
¥The handler.get()
method is a trap for the [[Get]]
object internal method, which is used by operations such as property accessors.
Try it
语法
参数
¥Parameters
以下参数传递给 get()
方法。this
绑定到处理程序。
¥The following parameters are passed to the get()
method. this
is bound to the handler.
target
-
目标对象。
property
-
表示属性名称的字符串或
Symbol
。 receiver
-
getter 的
this
值;见Reflect.get()
。这通常是代理本身或从代理继承的对象。
返回值
描述
拦截
¥Interceptions
该陷阱可以拦截以下操作:
¥This trap can intercept these operations:
- 属性准入:
proxy[foo]
和proxy.bar
Reflect.get()
或调用 [[Get]]
内部方法 的任何其他操作。
¥Or any other operation that invokes the [[Get]]
internal method.
不变量
¥Invariants
如果处理程序定义违反以下不变量之一,则代理的 [[Get]]
内部方法将抛出 TypeError
:
¥The proxy's [[Get]]
internal method throws a TypeError
if the handler definition violates one of the following invariants:
- 如果目标对象属性是不可写、不可配置的自有数据属性,则为属性报告的值必须与相应的目标对象属性的值相同。也就是说,如果
Reflect.getOwnPropertyDescriptor()
对target
上的属性返回configurable: false, writable: false
,则陷阱必须返回与target
的属性描述符中的value
属性相同的值。 - 如果相应的目标对象属性是具有未定义 getter 的不可配置自有访问器属性,则为属性报告的值必须是
undefined
。也就是说,如果Reflect.getOwnPropertyDescriptor()
对target
上的属性返回configurable: false, get: undefined
,则陷阱必须返回undefined
。
示例
获取属性价值的陷阱
¥Trap for getting a property value
以下代码捕获获取属性值的陷阱。
¥The following code traps getting a property value.
const p = new Proxy(
{},
{
get(target, property, receiver) {
console.log(`called: ${property}`);
return 10;
},
},
);
console.log(p.a);
// "called: a"
// 10
以下代码违反了不变量。
¥The following code violates an invariant.
const obj = {};
Object.defineProperty(obj, "a", {
configurable: false,
enumerable: false,
value: 10,
writable: false,
});
const p = new Proxy(obj, {
get(target, property) {
return 20;
},
});
p.a; // TypeError is thrown
规范
Specification |
---|
ECMAScript Language Specification # sec-proxy-object-internal-methods-and-internal-slots-get-p-receiver |
浏览器兼容性
BCD tables only load in the browser
也可以看看
¥See also