views:

1011

answers:

3

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.

+1  A: 

not that I know of... but you can add one easily.

jldupont
How? ...............
Tim Down
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
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
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
+1  A: 

No, but as you know, the language is easily extensible.

Upper Stage
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
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
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
+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