Adarchy
Adarchy

Reputation: 551

Javascript get name of instance of class

function myClass(a,b,c) {
     this.alertMyName=function(){alert(instancename)}

{...}


}

and then

foo = myClass(a,b,c);
boo = myClass(a,b,c);

foo.alertMyName(); //it should alert 'foo'
boo.alertMyName(); //it should alert 'boo'

In practice I'll need it for class that is creating a lot of html objects to prefix their ID's to differentiate them from same object created by another instance of this class.

Upvotes: 1

Views: 6807

Answers (3)

Kmeixner
Kmeixner

Reputation: 1752

I Couldn't find a solution on Stack Overflow so here is a solution I found from ronaldcs on dforge.net: http://www.dforge.net/2013/01/27/how-to-get-the-name-of-an-instance-of-a-class-in-javascript/

myObject = function () {
  this.getName = function () {
    // search through the global object for a name that resolves to this object
    for (var name in window)
      if (window[name] == this)
        return name;
  };
};

Try it Out:

var o = new myObject(); 
alert(o.getName()); // alerts "o"

Upvotes: 9

RobG
RobG

Reputation: 147363

Further to David's answer, variables in javascript have a value that is either a primitive or a reference to an object. Where the value is a reference, then the thing it references has no idea what the "name" of the variable is.

Consider:

var foo = new MyThing();
var bar = foo;

So now what should foo.alertMyName() return? Or even:

(new MyThing()).alertMyName();

If you want instances to have a name, then give them a property and set its value to whatever suits.

Upvotes: 3

David Hellsing
David Hellsing

Reputation: 108480

You could bring it in as a parameter:

function myClass(name, a, b, c) {
   this.alertMyName = function(){ alert(name) }
}

foo = new myClass('foo', a, b, c);

Or assign it afterwards:

function myClass(a, b, c) {
   this.setName = function(name) {
       this.name = name;
   }
   this.alertMyName = function(){ 
       alert(this.name)
   }
}

foo = new myClass( a,b,c);
foo.setName('foo');

Upvotes: 4

Related Questions