Created
July 25, 2012 17:19
-
-
Save karolk/3177365 to your computer and use it in GitHub Desktop.
new property descriptors syntax in javascript includes getters and 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 t = Object.create({}, { | |
__percent__: { | |
value: 0.01, | |
writable: true | |
}, | |
percent: { | |
get: function() { | |
return this.__percent__*100 | |
}, | |
set: function(v) { | |
return this.__percent__= Math.max( 0, Math.min( v, 100 ) ) / 100 | |
} | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example of how and why to use get/set property descriptors in JavaScript/ES5. By creating a property that uses get/set you can create a virtual property, that can implement magical behaviour. In this example percent property enables manipulating percent by assinging values between 1...100, but the value is stored on the object in a percent property using floating point number.