For browsers that implement the Object.defineProperty() method, the code below generates and returns a function that you can bind to any own object.
This approach has the advantage that it does not extend Object.prototype .
The code works by checking whether the given object has the __objectID__ property, and defining it as a hidden (non-enumerable) read-only property, if not.
Thus, it is safe against any attempt to change or override the read-only property obj.__objectID__ after it has been defined, and consistently produces a nice error instead of silence.
Finally, in a rather extreme case, when some other code has already defined __objectID__ for this object, this value will simply be returned.
var getObjectID = (function () { var id = 0; // Private ID counter return function (obj) { if(obj.hasOwnProperty("__objectID__")) { return obj.__objectID__; } else { ++id; Object.defineProperty(obj, "__objectID__", { /* * Explicitly sets these two attribute values to false, * although they are false by default. */ "configurable" : false, "enumerable" : false, /* * This closure guarantees that different objects * will not share the same id variable. */ "get" : (function (__objectID__) { return function () { return __objectID__; }; })(id), "set" : function () { throw new Error("Sorry, but 'obj.__objectID__' is read-only!"); } }); return obj.__objectID__; } }; })();
Luc125 Nov 23 '12 at 15:59 2012-11-23 15:59
source share