Created
November 21, 2011 20:09
-
-
Save StanAngeloff/1383769 to your computer and use it in GitHub Desktop.
Getters/Setters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var object = { | |
_property: 10, | |
// Getter/Setter | |
property: function(value) { | |
if (typeof (value) === 'undefined') { | |
return this._property; | |
} | |
this._property = value; | |
return this; | |
}, | |
// getProperty, setProperty is so Java | |
greet: function() { | |
return "Hello " + this._property + "!"; | |
} | |
}; | |
// no arguments acts like a getter | |
console.log( object.property() ); // prints 10 | |
// with an argument acts like a setter | |
object.property(20); // sets 20 | |
console.log( object.property() ); // prints 20 | |
// setters are chainable | |
console.log( object.property('Stan').greet() ); // prints 'Hello Stan!' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment