The set
syntax binds an object property to a function to be called when there is an attempt to set that property.
The set
syntax binds an object property to a function to be called when there is an attempt to set that property.
{ set prop(val) { /* … */ } } { set [expression](val) { /* … */ } }
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
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:
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
.
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(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"
Desktop | Mobile | Server | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js | |
set |
1 |
12 |
1.5 |
9 |
9.5 |
3 |
4.4 |
18 |
4 |
14 |
1 |
1.0 |
1.0 |
0.10.0 |
computed_property_names |
46 |
12 |
34 |
No |
47 |
9.1 |
46 |
46 |
34 |
33 |
9.3 |
5.0 |
1.0 |
4.0.0 |
delete
Object.defineProperty()
__defineGetter__
__defineSetter__
© 2005–2022 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/set