Last active
December 15, 2015 09:29
-
-
Save WebReflection/5238782 to your computer and use it in GitHub Desktop.
In current ES5 (all mobile browsers and all desktops but IE < 9) is possible to somehow simulate Harmony Symbol constructor.
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 Symbol; | |
if (!Symbol) { | |
Symbol = (function(Object){ | |
var defineProperty = Object.defineProperty, | |
prefix = '__simbol' + Math.random() + '__', | |
id = 0; | |
function Symbol() { | |
var self = this; | |
defineProperty( | |
Object.prototype, | |
self.__symbol__ = prefix + id++, | |
{ | |
enumerable: false, | |
configurable: true, | |
set: function set(value) { | |
defineProperty(this, self.__symbol__, { | |
enumerable: false, | |
configurable: true, | |
writable: true, | |
value: value | |
}); | |
} | |
} | |
); | |
} | |
defineProperty(Symbol.prototype, 'toString', { | |
enumerable: false, | |
writable: false, | |
configurable: false, | |
value: function toString() { | |
return this.__symbol__; | |
} | |
}); | |
return Symbol; | |
}(Object)); | |
} | |
// example | |
var sym = new Symbol; | |
var o = {}; | |
o[sym] = 123; | |
console.log(o[sym]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
blog entry about Symbols