setter

当尝试设置属性时,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
Desktop Mobile Server
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet Node.js
set Chrome Full support 1 Edge Full support 12 Firefox Full support 2 IE Full support 9 Opera Full support 9.5 Safari Full support 3 WebView Android Full support 1 Chrome Android Full support 18 Firefox Android Full support 4 Opera Android Full support Yes Safari iOS Full support Yes Samsung Internet Android Full support 1.0 nodejs Full support Yes
Computed property names Chrome Full support 46 Edge Full support 12 Firefox Full support 34 IE No support No Opera Full support 47 Safari No support No WebView Android Full support 46 Chrome Android Full support 46 Firefox Android Full support 34 Opera Android Full support Yes Safari iOS No support No Samsung Internet Android Full support 5.0 nodejs Full support Yes

Legend

Full support  
Full support
No support  
No support

相关链接