Skip to content

Instantly share code, notes, and snippets.

@foomin10
Created August 10, 2014 02:22
Show Gist options
  • Save foomin10/f87fe8cf9849b7394a2e to your computer and use it in GitHub Desktop.
Save foomin10/f87fe8cf9849b7394a2e to your computer and use it in GitHub Desktop.
[JavaScript] Object.definePropertyのラッパー ref: http://qiita.com/MizuiroFolder/items/a001977cdb267d65ef6b
function constant(key, value){
defProp(window, key, value, 1);
return value;
}
constant('FOO_BAR', 'foo bar') //=> 'foo bar'
FOO_BAR //=> 'foo bar'
FOO_BAR = 'baz' //=> 'baz'
FOO_BAR //=> 'foo bar'
(function(){ 'use strict'; FOO_BAR = 'baz' })() //~> TypeError: "FOO_BAR" is read-only
FOO_BAR //=> 'foo bar'
function defProp(targets, key, value, descriptorMask){
if(typeof descriptorMask === 'undefined') descriptorMask = 7
Object.defineProperty(targets, key, {
value: value,
enumerable: descriptorMask & 1, // 列挙可能か
configurable: descriptorMask & 2, // 削除可能か
writable: descriptorMask & 4, // 変更可能か
});
return targets;
}
defProp(Object.prototype, 'keys', function(){
return Object.keys(this);
}, 6); //=> Object.prototype
({ foo: 9, bar: 8 }).keys() //=> ['foo','bar']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment