Skip to content

Instantly share code, notes, and snippets.

@karolk
Created July 25, 2012 17:19
Show Gist options
  • Save karolk/3177365 to your computer and use it in GitHub Desktop.
Save karolk/3177365 to your computer and use it in GitHub Desktop.
new property descriptors syntax in javascript includes getters and setters
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
}
}
})
@karolk
Copy link
Author

karolk commented Jul 25, 2012

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment