2012-03-25 56 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?