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
语法
参数
返回值
¥Return value
set()
方法必须返回一个 Boolean
,指示赋值是否成功。其他值为 强制转换为布尔值。
¥The set()
method must return a Boolean
indicating whether or not the assignment succeeded. Other values are coerced to booleans.
如果 [[Set]]
内部方法返回 false
,则许多操作(包括在 严格模式 中使用属性访问器)都会抛出 TypeError
。
¥Many operations, including using property accessors in strict mode, throw a TypeError
if the [[Set]]
internal method returns false
.
描述
拦截
¥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.
不变量
¥Invariants
如果处理程序定义违反以下不变量之一,则代理的 [[Set]]
内部方法将抛出 TypeError
:
¥The proxy's [[Set]]
internal method throws a TypeError
if the handler definition violates one of the following invariants:
- 如果相应的目标对象属性是不可写、不可配置的自身数据属性,则无法将属性的值更改为与相应的目标对象属性的值不同。也就是说,如果
Reflect.getOwnPropertyDescriptor()
为target
上的属性返回configurable: false, writable: false
,而value
与target
的属性描述符中的value
属性不同,则陷阱必须返回一个假值。 - 如果相应的目标对象属性是具有未定义 setter 的不可配置的自身访问器属性,则无法设置属性的值。也就是说,如果
Reflect.getOwnPropertyDescriptor()
对target
上的属性返回configurable: false, set: undefined
,则陷阱必须返回一个假值。
示例
属性值的陷阱设置
¥Trap setting of a property value
以下代码捕获设置属性值。
¥The following code traps setting a property value.
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