Skip to content

Instantly share code, notes, and snippets.

@rwaldron
Created October 30, 2012 19:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rwaldron/eda4398feb774be889b1 to your computer and use it in GitHub Desktop.
Save rwaldron/eda4398feb774be889b1 to your computer and use it in GitHub Desktop.
Accessors via property descriptors
var C = (function() {
// Map requires --harmony flag
var map = new Map();
function C( initial ) {
// define accessor via property descriptor:
Object.defineProperties(this, {
square: {
get: function() {
return Math.pow( map.get(this).value || 0, 2 );
}
}
});
map.set(this, {
value: initial,
history: []
});
}
C.prototype = {
constructor: C,
get value() {
return map.get(this).value;
},
// Validate assignments and add to history
set value( val ) {
if ( typeof val !== "number" ) {
throw new TypeError("val must be a number");
}
// Save the previous value to the history
map.get(this).history.push( map.get(this).value );
return (map.get(this).value = val);
},
history: function( filterFn ) {
if ( !filterFn ) {
filterFn = function() { return true };
}
return map.get(this).history.filter( filterFn );
}
};
return C;
}());
var c = new C(10);
console.log( c.square ); // 100
console.log( c.value ); // 10
console.log( c.history() ); // []
c.value = 4;
console.log( c.history() ); // [ 10 ]
try {
c.value = "hi!";
} catch (e) {
console.log( e.message );
// TypeError: val must be a number
}
c.value = 5;
console.log( c.history() ); // [ 10, 4 ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment