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

分配最初针对的对象。这通常是代理本身。但是 set() 处理程序也可以通过原型链或各种其他方式间接调用。

例如,假设一个脚本做了 obj.name = "jen"obj 不是代理,并且没有自己的属性 .name,但它的原型链上有一个代理。该代理的 set() 处理程序将被调用,并且 obj 将作为接收者传递。

返回值

¥Return value

set() 方法应返回一个布尔值。

¥The set() method should return a boolean value.

  • 返回 true 表示赋值成功。
  • 如果 set() 方法返回 false,并且赋值发生在严格模式代码中,则会抛出 TypeError

描述

¥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

如果违反以下不变量,则陷阱在调用时会抛出 TypeError

¥If the following invariants are violated, the trap throws a TypeError when invoked.

  • 如果相应的目标对象属性是不可写、不可配置的数据属性,则无法将属性值更改为与相应目标对象属性的值不同。
  • 如果相应的目标对象属性是具有 undefined 作为其 [[Set]] 属性的不可配置访问器属性,则无法设置属性的值。
  • 在严格模式下,set() 处理程序的 false 返回值将引发 TypeError 异常。

示例

¥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

也可以看看