Reflect.set()

Reflect.set() 静态方法类似于 属性访问器assignment 语法,但作为一个函数。

¥The Reflect.set() static method is like the property accessor and assignment syntax, but as a function.

Try it

语法

¥Syntax

js
Reflect.set(target, propertyKey, value)
Reflect.set(target, propertyKey, value, receiver)

参数

¥Parameters

target

要设置属性的目标对象。

propertyKey

要设置的属性的名称。

value

要设置的值。

receiver Optional

提供的 this 值用于调用 target 上的 propertyKey 的 setter。如果提供并且 target 没有 propertyKey 的 setter,则该属性将在 receiver 上设置。

返回值

¥Return value

Boolean 指示设置属性是否成功。

¥A Boolean indicating whether or not setting the property was successful.

例外情况

¥Exceptions

TypeError

如果 target 不是对象,则抛出该异常。

描述

¥Description

Reflect.set() 提供 属性访问权 的反射语义。也就是说,Reflect.set(target, propertyKey, value, receiver) 在语义上等同于:

¥Reflect.set() provides the reflective semantic of a property access. That is, Reflect.set(target, propertyKey, value, receiver) is semantically equivalent to:

js
target[propertyKey] = value;

请注意,在正常的属性访问中,targetreceiver 显然是同一个对象。

¥Note that in a normal property access, target and receiver would observably be the same object.

Reflect.set() 调用 target[[Set]] 对象内部方法

¥Reflect.set() invokes the [[Set]] object internal method of target.

示例

¥Examples

使用 Reflect.set()

¥Using Reflect.set()

js
// Object
const obj = {};
Reflect.set(obj, "prop", "value"); // true
obj.prop; // "value"

// Array
const arr = ["duck", "duck", "duck"];
Reflect.set(arr, 2, "goose"); // true
arr[2]; // "goose"

// It can truncate an array.
Reflect.set(arr, "length", 1); // true
arr; // ["duck"]

// With just one argument, propertyKey and value are "undefined".
Reflect.set(obj); // true
Reflect.getOwnPropertyDescriptor(obj, "undefined");
// { value: undefined, writable: true, enumerable: true, configurable: true }

不同的目标和接收器

¥Different target and receiver

targetreceiver 不同时,Reflect.set 会使用 target 的属性描述符(查找 setter 或确定属性是否可写),但在 receiver 上设置属性。

¥When the target and receiver are different, Reflect.set will use the property descriptor of target (to find the setter or determine if the property is writable), but set the property on receiver.

js
const target = {};
const receiver = {};
Reflect.set(target, "a", 2, receiver); // true
// target is {}; receiver is { a: 2 }

const target = { a: 1 };
const receiver = {};
Reflect.set(target, "a", 2, receiver); // true
// target is { a: 1 }; receiver is { a: 2 }

const target = {
  set a(v) {
    this.b = v;
  },
};
const receiver = {};
Reflect.set(target, "a", 2, receiver); // true
// target is { a: [Setter] }; receiver is { b: 2 }

规范

Specification
ECMAScript Language Specification
# sec-reflect.set

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看