Created
August 10, 2014 02:22
-
-
Save foomin10/f87fe8cf9849b7394a2e to your computer and use it in GitHub Desktop.
[JavaScript] Object.definePropertyのラッパー ref: http://qiita.com/MizuiroFolder/items/a001977cdb267d65ef6b
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
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' |
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
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; | |
} |
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
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