Created
May 10, 2016 05:01
-
-
Save Klortho/1a630f755c818bbc606eb104d78008db to your computer and use it in GitHub Desktop.
Set a unique id property _uid on all objects.
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
// Generates a unique, read-only id for any object. This modifies Object.prototype, | |
// so should only be used for testing, within a limited scope. | |
// The _uid is generated for an object the first time it's accessed. | |
(function() { | |
var id = 0; | |
Object.defineProperty(Object.prototype, '_uid', { | |
// The prototype getter sets up a property on the instance. Because | |
// the new instance-prop masks this one, we know this will only ever | |
// be called at most once for any given object. | |
get: function () { | |
Object.defineProperty(this, '_uid', { | |
value: id++, | |
writable: false, | |
enumerable: false, | |
}); | |
return this._uid; | |
}, | |
enumerable: false, | |
}); | |
})(); | |
function assert(p) { if (!p) throw Error('Not!'); } | |
var obj = {}; | |
assert(obj._uid == 0); | |
assert({}._uid == 1); | |
assert([]._uid == 2); | |
assert(obj._uid == 0); // still |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment