This question already has an answer here:
- unique object identifier in javascript 11 answers
Do JavaScript objects/variables have some sort of unique identifier? Like Ruby has object_id
. I don't mean the DOM id attribute, but rather some sort of memory address of some kind.
Using ES6 + Symbols.
Use ES6 Module export for Symbol if unique symbol is preferred, otherwise go with Symbo
If you want to lookup/associate an object with a unique identifier without modifying the underlying object, you can use a
WeakMap
:Using a
WeakMap
ensures that the objects can still be garbage-collected.Using ES6 + Symbols.
Use ES6 Module export for Symbol if unique symbol is preferred, otherwise go with Symbols in global registry.
I've just come across this, and thought I'd add my thoughts. As others have suggested, I'd recommend manually adding IDs, but if you really want something close to what you've described, you could use this:
You can get any object's ID by calling
objectId(obj)
. Then if you want the id to be a property of the object, you can either extend the prototype:or you can manually add an ID to each object by adding a similar function as a method.
The major caveat is that this will prevent the garbage collector from destroying objects when they drop out of scope... they will never drop out of the scope of the
allObjects
array, so you might find memory leaks are an issue. If your set on using this method, you should do so for debugging purpose only. When needed, you can doobjectId.clear()
to clear theallObjects
and let the GC do its job (but from that point the object ids will all be reset).Actually, you don't need to modify the
object
prototype. The following should work to 'obtain' unique ids for any object, efficiently enough.No, objects don't have a built in identifier, though you can add one by modifying the object prototype. Here's an example of how you might do that:
That said, in general modifying the object prototype is considered very bad practice. I would instead recommend that you manually assign an id to objects as needed or use a
touch
function as others have suggested.