setter - JavaScript 编辑

The set syntax binds an object property to a function to be called when there is an attempt to set that property.

Syntax

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

Parameters

prop
The name of the property to bind to the given function.
val
An alias for the variable that holds the value attempted to be assigned to prop.
expression
Starting with ECMAScript 2015, you can also use expressions for a computed property name to bind to the given function.

Description

In JavaScript, a setter can be used to execute a function whenever a specified property is attempted to be changed. Setters are most often used in conjunction with getters to create a type of pseudo-property. It is not possible to simultaneously have a setter on a property that holds an actual value.

Note the following when working with the set syntax:

Examples

Defining a setter on new objects in object initializers

The following example define a pseudo-property current of object language. When current is assigned a value, it updates log with that value:

const 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']

Note that current is not defined, and any attempts to access it will result in undefined.

Removing a setter with the delete operator

If you want to remove the setter, you can just delete it:

delete language.current;

Defining a setter on existing objects using defineProperty

To append a setter to an existing object, use Object.defineProperty().

const 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

Using a computed property name

const expr = 'foo';

const 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"

Specifications

Specification
ECMAScript (ECMA-262)
The definition of 'Method definitions' in that specification.

Browser compatibility

BCD tables only load in the browser

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:87 次

字数:6993

最后编辑:7 年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文