Skip to content

Instantly share code, notes, and snippets.

@anasnakawa
Last active August 29, 2015 14:00
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anasnakawa/11167816 to your computer and use it in GitHub Desktop.
Save anasnakawa/11167816 to your computer and use it in GitHub Desktop.
mocking constant behaviour using `Object.defineProperty`, works on real browsers & IE9+
/**
* 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