set
syntax binds an object property to a function to be called when there is an attempt to set that property.
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
{set prop(val) { . . . }}
{set [expression](val) { . . . }}
prop
The name of the property to bind to the given function.
val
prop
.
expression
Starting with ECMAScript 2015, you can also use expressions for a computed property name to bind to the given function.
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:
set
or with a data entry for the same property.
{ set x(v) { }, set x(v) { } }
and
{ x: ..., set x(v) { } }
are forbidden )
The following example define a pseudo-property
current
of object
language
。当
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']
注意,
current
is not defined, and any attempts to access it will result in
undefined
.
delete
operator
If you want to remove the setter, you can just
delete
it:
delete language.current;
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
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"
| 规范 |
|---|
|
ECMAScript (ECMA-262)
The definition of 'Method definitions' in that specification. |
| Desktop | Mobile | Server | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
set
|
Chrome 1 | Edge 12 | Firefox 1.5 | IE 9 | Opera 9.5 | Safari 3 | WebView Android 1 | Chrome Android 18 | Firefox Android 4 | Opera Android 14 | Safari iOS 1 | Samsung Internet Android 1.0 | nodejs Yes |
| Computed property names | Chrome 46 | Edge 12 | Firefox 34 | IE No | Opera 47 | Safari No | WebView Android 46 | Chrome Android 46 | Firefox Android 34 | Opera Android 33 | Safari iOS No | Samsung Internet Android 5.0 | nodejs Yes |
完整支持
不支持
delete
Object.defineProperty()
__defineGetter__
__defineSetter__