当尝试设置属性时,set语法将对象属性绑定到要调用的函数。

语法

{set prop(val) { . . . }}
{set [expression](val) { . . . }}

参数

prop
要绑定到给定函数的属性名。
val
用于保存尝试分配给prop的值的变量的一个别名。
表达式
从 ECMAScript 2015 开始,还可以使用一个计算属性名的表达式绑定到给定的函数。

描述

在 javascript 中,如果试着改变一个属性的值,那么对应的 setter 将被执行。setter 经常和 getter 连用以创建一个伪属性。不可能在具有真实值的属性上同时拥有一个 setter 器。

使用 set 语法时请注意:

setter 可以用delete操作来移除。

示例

在对象初始化时定义 setter

这将定义一个对象 language 的伪属性current,当分配一个值时,将使用该值更新log

var language = {
  set current(name) {
    this.log.push(name);
  },
  log: []
}

language.current = 'EN';
console.log(language.log); // ['EN']

language.current = 'FA';
console.log(language.log); // ['EN', 'FA']

请注意,current属性是未定义的,访问它时将会返回 undefined

delete 操作符移除一个 setter

我们可以使用delete操作符移除 setter。

delete o.current;

使用 defineProperty 为当前对象定义 setter

我们可以随时使用 Object.defineProperty() 给一个已经存在的对象添加一个 setter。

var o = { a:0 };

Object.defineProperty(o, "b", { set: function (x) { this.a = x / 2; } });

o.b = 10; // Runs the setter, which assigns 10 / 2 (5) to the 'a' property
console.log(o.a) // 5

使用计算属性名

var expr = "foo";

var obj = {
  baz: "bar",
  set [expr](v) { this.baz = v; }
};

console.log(obj.baz); // "bar"
obj.foo = "baz";      // run the setter
console.log(obj.baz); // "baz"

规范

Specification Status Comment
ECMAScript 5.1 (ECMA-262)
Object Initializer
Standard Initial definition.
ECMAScript 2015 (6th Edition, ECMA-262)
Method definitions
Standard Added computed property names.
ECMAScript Latest Draft (ECMA-262)
Method definitions
Draft  

浏览器兼容

Update compatibility data on GitHub
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidEdge MobileFirefox for AndroidOpera for AndroidiOS SafariSamsung InternetNode.js
Basic supportChrome Full support 1Edge Full support YesFirefox Full support 2IE Full support 9Opera Full support 9.5Safari Full support 3WebView Android Full support 1Chrome Android Full support 18Edge Mobile Full support YesFirefox Android Full support 4Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yesnodejs Full support Yes
Computed property namesChrome Full support 46Edge Full support YesFirefox Full support 34IE No support NoOpera Full support 47Safari No support NoWebView Android Full support 46Chrome Android Full support 46Edge Mobile Full support YesFirefox Android Full support 34Opera Android Full support YesSafari iOS No support NoSamsung Internet Android Full support 5.0nodejs Full support Yes

Legend

Full support  
Full support
No support  
No support

相关链接

文档标签和贡献者

最后编辑者: fscholz,