Last active
August 29, 2015 14:00
-
-
Save anasnakawa/11167816 to your computer and use it in GitHub Desktop.
mocking constant behaviour using `Object.defineProperty`, works on real browsers & IE9+
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
/** | |
* simulating constant behaviour where | |
* given value cannot be changed | |
* | |
* @param {object} target object where the constant will be defined | |
* @param {string} key | |
* @param {object} value | |
* @return {object} constant | |
* | |
* example | |
* ------- | |
* Constant( 'cantTouchThis', 99 ); | |
* cantTouchThis; // 99 | |
* cantTouchThis = 200; // 99 | |
*/ | |
function Constant( key, value, target ) { | |
target = target || window; | |
if( value == null ) { | |
throw new Error( 'constant should have a value at the time of creation' ); | |
} | |
Object.defineProperty( target, key, { value : value, enumerable: true }); | |
return target[ key ]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment