2012-03-25 53 views
1

有没有办法获得this所指的对象的确切名称,而不仅仅是object Object我怎样才能得到究竟什么。这是指向

+0

对象的名称?在变量名称中?如果是这样,不。 – mpen 2012-03-25 18:15:19

+0

你是否在做任何事情来提醒对象? – pimvdb 2012-03-25 18:26:15

回答

3

不,没有。 JavaScript中的对象本身并不具有名称。相反,它有一组指向它的命名引用(或可能没有)。 this值只是其中的一个参考。

// 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; 
2

没有,但你可以看到什么this在任何给定时间转储到控制台:

console.log(this);

0

“本”也只是另一个别名你的对象,有可能是许多指向与“this”相同的变量名指向。没有已知的方法来获取对象创建的原始名称(如果有的话)。你可以得到的最好的是类型“这个”

Object.prototype.toString.call(this)

1

你可以尝试这样的事情,即使它不会在某些情况下工作:

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

希望这有助于。 也许你还想看看这篇文章:How to get class object's name as a string in Javascript?