Core JavaScript 1.5 Reference:Operators:Special Operators:set Operator
From MDC
Contents |
[edit] Summary
Binds an object property to a function to be called when there is an attempt to set that property.
[edit] Syntax
{set prop [ fun ](val) { . . . }
[edit] Parameters
-
prop - the name of the property to bind to the given function
-
funname - the (optional) name of the function to bind to the specified property.
-
val - an alias for the variable that holds the value attempted to be assigned to
prop
[edit] 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.
A setter can be removed using the delete Operator.
[edit] Examples
[edit] Example: 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
[edit] Example: Removing a setter with the delete operator
delete o.current;