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.
views:
1011answers:
3How? ...............
Tim Down
2010-01-07 13:58:46
My favorite way to create a unique value is using the ExtJS id() function. The code is only a few lines long and easy to replicate, but essentially it increments a shared number and appends a "pretty" string to it. Every call to the function increments the shared counter, so every caller is guarenteed a unique value.
Upper Stage
2010-01-07 14:05:37
See http://softwareas.com/guid0-a-javascript-guid-generator : use the id generated and add a "uid" property to the object(s) you want.
jldupont
2010-01-07 14:06:39
Sorry, I wasn't clear. What I really wanted to know was how you'd have the object id assigned to all objects as they're created, but I guess the OP didn't actually ask that.
Tim Down
2010-01-08 09:52:47
OK, but what's your take on this? Do you have any other attributes in mind that might generate a unique id when combined?
treznik
2010-01-07 13:54:11
2 questions... 1.) why do you want to add one? e.g. whats the reason? and 2.) if the JS objects you are wanting are DOM objects, you could always add some sort of touch() function that assigns a unique id to the objects you care about.
scunliffe
2010-01-07 13:58:28
My favorite way to create a unique value in JS is using the ExtJS id() function. The code is only a few lines long and easy to replicate, but essentially it increments a shared number and appends a "pretty" string to it. Every call to the function increments the shared counter, so every caller is guarenteed a unique value. I typically place the function in a utility namespace; one could call it from a constructor to solve the problem posed herein.
Upper Stage
2010-01-07 14:05:00
+2
A:
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:
(function() {
var id = 0;
function generateId() { return id++; };
Object.prototype.id = function() {
var newId = generateId();
this.id = function() { return newId; };
return newId;
};
})();
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.
Xavi
2010-01-07 14:14:45