handler.set()
handler.set()
方法是 [[Set]]
对象内部方法 的陷阱,它被诸如使用 属性访问器 设置属性值之类的操作所使用。
¥The handler.set()
method is a trap for the [[Set]]
object internal method, which is used by operations such as using property accessors to set a property's value.
Try it
语法
参数
¥Parameters
以下参数传递给 set()
方法。this
绑定到处理程序。
¥The following parameters are passed to the set()
method. this
is bound to the handler.
返回值
¥Return value
set()
方法应返回一个布尔值。
¥The set()
method should return a boolean value.
- 返回
true
表示赋值成功。 - 如果
set()
方法返回false
,并且赋值发生在严格模式代码中,则会抛出TypeError
。
描述
拦截
¥Interceptions
该陷阱可以拦截以下操作:
¥This trap can intercept these operations:
- 属性分配:
proxy[foo] = bar
和proxy.foo = bar
Reflect.set()
或调用 [[Set]]
内部方法 的任何其他操作。
¥Or any other operation that invokes the [[Set]]
internal method.
不变量
示例
属性值的陷阱设置
¥Trap setting of a property value
以下代码捕获设置属性值。
¥The following code traps setting a property value.
js
const p = new Proxy(
{},
{
set(target, prop, value, receiver) {
target[prop] = value;
console.log(`property set: ${prop} = ${value}`);
return true;
},
},
);
console.log("a" in p); // false
p.a = 10; // "property set: a = 10"
console.log("a" in p); // true
console.log(p.a); // 10
规范
Specification |
---|
ECMAScript Language Specification # sec-proxy-object-internal-methods-and-internal-slots-set-p-v-receiver |
浏览器兼容性
BCD tables only load in the browser
也可以看看
¥See also