Object IDs
There are plenty of times where you have an object and would like to uniquely identify it, either to aid in debugging or to use the Unique ID (UID) as a lookup key. While extending built-in types is generally not a good idea, doing so to aid development and debugging is a worthwhile exception.
Why is this useful?
Occasionally while debugging you want to uniquely identify objects either for purposes of ensuring that you are looking at the same object at multiple point in your data flow, or using the objects’ UID to trigger a tracepoint (A breakpoint with a conditional - in this case a conditional on the object ID). Tracepoints are particularly useful when you are iterating over a large number of objects while only a specific one of them is causing an issue.
Explanation
Giving all objects a UID is easily done by taking advantage of the Object.defineProperty function (read more about it here). By defining new properties on Object.prototype, you guarantee that every object created will have a valid ID that is created on demand.
Source Code
if (typeof Object.prototype.uniqueID === 'undefined')
{
// Counter that provides a unique ID for each object. Incremented on demand.
var nextUniqueId = 0;
// Non-visible and non-iterable property for an object that stores the UID
Object.defineProperty(Object.prototype, '__uniqueID',
{
writable: true
});
// Non-writable accessor for an objects UID. Will generate and assign the UID
// on demand.
Object.defineProperty(Object.prototype, 'uniqueID',
{
get: function()
{
// Only ever generate and assign a single UID for an object
if (this.__uniqueID === undefined)
{
this.__uniqueID = ++nextUniqueId;
}
return this.__uniqueID;
}
});
}