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

语法

¥Syntax

js
new Proxy(target, {
  set(target, property, value, receiver) {
  }
})

参数

¥Parameters

以下参数传递给 set() 方法。this 绑定到处理程序。

¥The following parameters are passed to the set() method. this is bound to the handler.

target

目标对象。

property

表示属性名称的字符串或 Symbol

value

要设置的属性的新值。

receiver

setter 的 this 值;见 Reflect.set()。这通常是代理本身或从代理继承的对象。

返回值

¥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.

描述

¥Description

拦截

¥Interceptions

该陷阱可以拦截以下操作:

¥This trap can intercept these operations:

  • 属性分配:proxy[foo] = barproxy.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,而 valuetarget 的属性描述符中的 value 属性不同,则陷阱必须返回一个假值。
  • 如果相应的目标对象属性是具有未定义 setter 的不可配置的自身访问器属性,则无法设置属性的值。也就是说,如果 Reflect.getOwnPropertyDescriptor()target 上的属性返回 configurable: false, set: undefined,则陷阱必须返回一个假值。

示例

¥Examples

属性值的陷阱设置

¥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

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看