开发者

javascript 'this' - how to find text name of object this points to

How to find the text description of what 'this' currently开发者_C百科 points to in javascript.

i have tried this.name but just get undefined.


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


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.


Well there's always typeof:

var type = typeof obj;

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


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


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.


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];
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜