静态方法 Reflect.set() 工作方式就像在一个对象上设置一个属性。

语法

Reflect.set(target, propertyKey, value[, receiver])

参数

target
设置属性的目标对象。
propertyKey
设置的属性的名称。
value
设置的值。
receiver
如果遇到 setter,this 将提供给目标调用。

返回值

返回一个 Boolean 值表明是否成功设置属性。

异常

抛出一个 TypeError,如果目标不是 Object

描述

Reflect.set 方法允许你在对象上设置属性。它的作用是给属性赋值并且就像 property accessor 语法一样,但是它是以函数的方式。 

示例

使用 Reflect.set()

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

// Array
var 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".
var obj = {};
Reflect.set(obj); // true
Reflect.getOwnPropertyDescriptor(obj, "undefined");
// { value: undefined, writable: true, enumerable: true, configurable: true }

规范

Specification Status Comment
ECMAScript 2015 (6th Edition, ECMA-262)
Reflect.set
Standard Initial definition.
ECMAScript Latest Draft (ECMA-262)
Reflect.set
Draft  

浏览器兼容性

Update compatibility data on GitHub
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidEdge MobileFirefox for AndroidOpera for AndroidSafari on iOSSamsung InternetNode.js
setChrome Full support 49Edge Full support 12Firefox Full support 42IE No support NoOpera Full support 36Safari Full support 10WebView Android Full support 49Chrome Android Full support 49Edge Mobile Full support YesFirefox Android Full support 42Opera Android Full support 36Safari iOS Full support 10Samsung Internet Android Full support 5.0nodejs Full support 6.0.0

Legend

Full support  
Full support
No support  
No support

相关链接