1

Is there a way to get the exact name of the object that this is referring to and not just object Object?

ilyo
  • 35,851
  • 46
  • 106
  • 159

4 Answers4

3

No there is not. An object in javascript doesn't inherently have a name. Instead it has a set of named references which point to it (or possibly none). The this value is just one of these references.

// The {} is an object without a name. Here 'x' is a reference
// to that object
var x = {};  

// Now 'y' refers to the same object as 'x'.  But neither 'x' 
// nor 'y' is the name of the object. 
var y = x;
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
2

No, but you can see what this is at any given time by dumping to the console:

console.log(this);

AlienWebguy
  • 76,997
  • 17
  • 122
  • 145
1

You could try something like this, even though it will not work in some cases:

 function R3S (){
    this.a = function(){
    whoIs(this);
    }
 }

 function whoIs(obj) {
     console.log(/(\w+)\(/.exec(obj.constructor.toString())[1]);
 }

 var t = new R3S();
 whoIs(t);
 t.a();

 var l = t;
 l.a();

Hope this helps. Maybe you would want to take a look at this post also : How to get class object's name as a string in Javascript?

Community
  • 1
  • 1
khael
  • 2,600
  • 1
  • 15
  • 36
0

"this" is also just another alias to your object, there could be many variable names pointing to the same this as "this" points to. There is no known way to get the original name the object was created with(if any). The best you could get is the type of "this"

Object.prototype.toString.call(this)

adentum
  • 982
  • 1
  • 11
  • 21