-
-
Save rwaldron/eda4398feb774be889b1 to your computer and use it in GitHub Desktop.
Accessors via property descriptors
This file contains 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 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