set

set 语法将对象属性绑定到要在尝试设置该属性时调用的函数。也可用于 classes

¥The set syntax binds an object property to a function to be called when there is an attempt to set that property. It can also be used in classes.

Try it

语法

¥Syntax

js
{ set prop(val) { /* … */ } }
{ set [expression](val) { /* … */ } }

还有一些额外的语法限制:

¥There are some additional syntax restrictions:

  • 一个 setter 必须只有一个参数。

参数

¥Parameters

prop

要绑定到给定函数的属性的名称。与 对象初始值设定项 中的其他属性一样,它可以是字符串文字、数字文字或标识符。

val

保存尝试分配给 prop 的值的变量的别名。

expression

你还可以使用计算属性名称的表达式来绑定到给定的函数。

描述

¥Description

在 JavaScript 中,只要尝试更改属性的值,就可以使用 setter 来执行函数。setter 最常与 getter 结合使用。

¥In JavaScript, a setter can be used to execute a function whenever an attempt is made to change a property's value. Setters are most often used in conjunction with getters.

对象属性要么是数据属性,要么是访问器属性,但不能同时是两者。阅读 Object.defineProperty() 了解更多信息。setter 语法允许你在对象初始值设定项中指定 setter 函数。

¥An object property is either a data property or an accessor property, but it cannot simultaneously be both. Read Object.defineProperty() for more information. The setter syntax allows you to specify the setter function in an object initializer.

js
const obj = {
  set prop() {
    // setter, the code executed when setting obj.prop
  },
}

使用此语法定义的属性是创建的对象自己的属性,并且它们是可配置和可枚举的。

¥Properties defined using this syntax are own properties of the created object, and they are configurable and enumerable.

示例

¥Examples

在对象初始值设定项中为新对象定义 setter

¥Defining a setter on new objects in object initializers

以下示例定义对象 language 的伪属性 current。当 current 被赋值时,它会用该值更新 log

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

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

请注意,current 未定义,任何访问它的尝试都将导致 undefined

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

在类中使用 setter

¥Using setters in classes

你可以使用完全相同的语法来定义类实例上可用的公共实例设置器。在类中,方法之间不需要逗号分隔符。

¥You can use the exact same syntax to define public instance setters that are available on class instances. In classes, you don't need the comma separator between methods.

js
class ClassWithGetSet {
  #msg = "hello world";
  get msg() {
    return this.#msg;
  }
  set msg(x) {
    this.#msg = `hello ${x}`;
  }
}

const instance = new ClassWithGetSet();
console.log(instance.msg); // "hello world"

instance.msg = "cake";
console.log(instance.msg); // "hello cake"

Setter 属性在类的 prototype 属性上定义,因此由该类的所有实例共享。与对象字面量中的 setter 属性不同,类中的 setter 属性是不可枚举的。

¥Setter properties are defined on the prototype property of the class and are thus shared by all instances of the class. Unlike setter properties in object literals, setter properties in classes are not enumerable.

静态 setter 和私有 setter 使用类似的语法,如 static私有属性 页中所述。

¥Static setters and private setters use similar syntaxes, which are described in the static and private properties pages.

使用 delete 操作器移除设定器

¥Removing a setter with the delete operator

如果你想删除 setter,你可以只 delete 它:

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

js
delete language.current;

使用 defineProperty 在现有对象上定义 setter

¥Defining a setter on existing objects using defineProperty

要将 setter 附加到现有对象,请使用 Object.defineProperty()

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

js
const o = { a: 0 };

Object.defineProperty(o, "b", {
  set(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

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

规范

Specification
ECMAScript Language Specification
# sec-method-definitions

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看