Reflect.set()
Reflect.set()
静态方法类似于 属性访问器 和 assignment 语法,但作为一个函数。
¥The Reflect.set()
static method is like the property accessor and assignment syntax, but as a function.
Try it
语法
参数
¥Parameters
target
-
要设置属性的目标对象。
propertyKey
-
要设置的属性的名称。
value
-
要设置的值。
receiver
Optional-
提供的
this
值用于调用target
上的propertyKey
的 setter。如果提供并且target
没有propertyKey
的 setter,则该属性将在receiver
上设置。
返回值
例外情况
描述
¥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:
target[propertyKey] = value;
请注意,在正常的属性访问中,target
和 receiver
显然是同一个对象。
¥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
.
示例
使用 Reflect.set()
¥Using Reflect.set()
// 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
当 target
和 receiver
不同时,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
.
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 |
浏览器兼容性
BCD tables only load in the browser