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

- 35,851
- 46
- 106
- 159
-
Name of the object? As in variable name? If so, no. – mpen Mar 25 '12 at 18:15
-
Are you doing something like alerting the object by any chance? – pimvdb Mar 25 '12 at 18:26
4 Answers
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;

- 733,204
- 149
- 1,241
- 1,454
No, but you can see what this
is at any given time by dumping to the console:
console.log(this);

- 76,997
- 17
- 122
- 145
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?
"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)

- 982
- 1
- 11
- 21