Table of contents
Summary
Binds an object property to a function to be called when there is an attempt to set that property.
Syntax
{set prop(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
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.
JavaScript 1.8.1 note
Starting in JavaScript 1.8.1, setters are no longer called when setting properties in object and array initializers.
JavaScript 1.8.5 note
Starting in JavaScript 1.8.5, set operator:
- can have an identifier which is either a number or a string;
- must have exactly one parameter (see Incompatible ES5 change: literal getter and setter functions must now have exactly zero or one arguments for more information);
- must not appear in an object literal with another
setor with a data entry for the same property ({ set x(v) { }, set x(v) { } }and{ x: ..., set x(v) { } }are forbidden).
A setter can be removed using the delete operator.
Examples
Defining a setter with the set operator
This will define a pseudo-property current of object o that, when assigned a value, will update log with that value:
var o = {
set current (str) {
return this.log[this.log.length] = str;
},
log: []
}
Note that current is not defined and any attempts to access it will result in undefined
Removing a setter with the delete operator
delete o.current;
Browser compatibility
Based on Robert Nyman's page
No support (notably in IE6-8) means that the script will trigger a syntax error.
| Feature | Firefox (Gecko) | Chrome | Internet Explorer | Opera | Safari |
|---|---|---|---|---|---|
| Basic support | 2.0 (1.8.1) | 1 | 9 | 9.5 | 3 |
| Feature | Firefox Mobile (Gecko) | Android | IE Mobile | Opera Mobile | Safari Mobile |
|---|---|---|---|---|---|
| Basic support | ? | ? | ? | ? | ? |
See also
deleteget__defineGetter____defineSetter__- Defining Getters and Setters in JavaScript Guide
Mozilla Developer Network