1
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.

2
  • You can pass instance name as parameter or use this. Commented Oct 19, 2012 at 10:25
  • alert(this) returns [object Object] Commented Oct 19, 2012 at 10:28

3 Answers 3

9

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"
Sign up to request clarification or add additional context in comments.

2 Comments

I'm surprised this answer hasn't received much attention.
This works like a champ in a class. Note: The value returned will be the first variable name assigned when an object is instantiated - For example, var a=new foo(); var b=a; var c=b; console.log(c.getName()); //Displays "a"
4

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');

3 Comments

is it really the only way to do this?
AFAIK, you can’t get a string "representation" of any variable in javascript, partly because it could be a reference to another object.
There are other ways, but they are essentially the same.
3

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.