tags:

views:

88

answers:

6

How to find the text description of what 'this' currently points to in javascript.

i have tried this.name but just get undefined.

+2  A: 

this.toString() - I think that's the best you can get

EDIT: You can also try looping through the object's properties to see what it contains:

for (property in this) {
    console.log(property);
}
Gabi Purcaru
A: 

Well there's always typeof:

var type = typeof obj;

But, this is not foolproof as you will just get 'object' for objects...

Michael Goldshteyn
A: 

If you're using Firebug you can use console.log(this). The console should then provide a clickable representation of whatever you've just logged, and clicking on it should take you to a more detailed explanation.

DanMan
Thats great - thanks. How does firebug do this then. Its exactly what i was looking for
David
`console.log()` works in Opera (Dragonfly) and Chrome (Web Inspector, I think it's called) *as well as* Firefox.
David Thomas
You're welcome. Good question - I don't really know. :)
DanMan
@David: I don't think there's a current mainstream browser that doesn't support *console.log()*
Andy E
@Andy E, you're probably right, but I was only really responding to the statement that "[if he's] using Firebug [he] can use `console.log(this)`."
David Thomas
@David, yes, the answer is a little misleading. Other browser vendors caught on to how useful firebug is quite a while ago :)
Andy E
@Andy E: there's always firebug lite!
Gabi Purcaru
A: 

Well, I'm still not entirely sure what you're wanting, but I've put this demo together, at JS Fiddle to give you an idea of a couple of the options available.

It rests on using:

$('#result').text(this.tagName.toLowerCase());

or

$('#result').text(typeof this);
David Thomas
A: 

Objects don't have names in JavaScript, it's as simple as that. A variable with a particular name could have an object as it's value, but that's as far as the relationship goes, the object retains no reference to the variable name that points to it. In fact, more than one variable may point to it. If a reference to an object is stored as a property on another object, you could iterate over that object's properties checking to see if the current property's value is the same object in the this value. For instance:

for (var k in someObj) {
    if (this == someObj[k])
        console.log(k + " points to this.");
}

I don't think there's a reason you'd ever need to do this, however.

Andy E
A: 

No Firebug required (demo at http://jsfiddle.net/Y57ed/2/):

function usefulTypeof(obj) {
    return obj === null ? "null" :
        obj.constructor.toString().replace(/[^\w$\s]+/g, "").split(/\s+/)[1];
}
idealmachine