2015-06-21 105 views
0

在JavaScript中,如何獲取聲明新對象的變量的名稱。如何獲取聲明新對象的變量的名稱

function asdf() { 
     this.dosomething = functon() { 
      var a = 1; 
     }; 
    } 

    var qwer = new asdf(); 

雖然航空自衛隊的範圍內(),我希望能夠找出創建該對象的此實例變量名。

+0

變量名應該被視爲元數據,不應該影響運行時行爲(除非你真的在做元編程)。 –

回答

1

你不能。實際上,變量根本不創建對象。該變量只包含對該對象的引用,但可能有多個這樣的引用。

另外,應該不需要它。在asdf之內,您可以使用關鍵字this來引用實例本身,該實例將與qwer所引用的實例相同。

如果您需要在asdf太方法裏面的情況,你可以創建一個局部變量的對象,像這樣:

function asdf() { 
    var memyself = this; // Store reference to `this` 
    this.dosomething = functon() { 
     var a = 1; 
     // Use stored reference, because `this` will refer to `dosomething` here. 
     mymyself.dosomethingelse(); 
    }; 

    this.dosomethingelse = functon() { 
     alert('hello'); 
    }; 
} 

var qwer = new asdf(); 

另一個例子,讓綁定的對象本身的元素的事件。我故意將名稱放在HTML中,但是您甚至可以從一組名稱中生成所有HTML。開頭的HTML應該只包含一個元素,以便在其中添加每個名稱的div。

你的對象可能是一個負責div的生命週期的人。如果你創建一個名字作爲參數的對象,它可以創建一個div,添加文本,附加事件處理程序,甚至刪除div。下面的代碼片段並不那麼先進,它只是查找元素並將其方法之一附加到該元素的單擊事件。

function asdf(element) { 
 
    // If element is a string, use it as id to fetch an actual element. 
 
    // (Some error checking required in prodction code). 
 
    if (typeof element === "string") { 
 
    element = document.getElementById(element); 
 
    } 
 
    // Store references to myself and my element. 
 
    var me = this; 
 
    me.element = element; // 'this' could be used instead of 'me'. 
 
    
 
    // Declare method 
 
    this.doSomething = function() { 
 
    alert(me.element.innerText); // Here, 'me' is required. 
 
    } 
 
    
 
    // Bind method to click event. 'this' could be used instead of 'me'. 
 
    me.element.addEventListener('click', this.doSomething); 
 
} 
 

 
// Create three object for the three elements. 
 

 
// You may store the object in a variable 
 
a = new asdf('john'); 
 
// But you don't even need to. The object can just exist without external 
 
// reference (well, apart from the element which still uses its event handler). 
 
new asdf('jane'); 
 
new asdf('nick');
Click a name to alert it. 
 
<div class="button" id="john">John Doe</div> 
 
<div class="button" id="jane">Jane Da</div> 
 
<div class="button" id="nick">Nick Name</div>

我希望這是你正在試圖解決這個問題,這個解決它。如果您仍然需要訪問quer,那麼您可能實施了糟糕的設計。如果您指定更多詳細信息,我(或其他人)可能會爲您找到更好的解決方案。

+0

我試圖弄清楚這個的原因是我可以在動態創建的html中調用onclick =「qwer.dosomething()」。我現在所做的只是將變量qwer的名字作爲參數的一部分,當我定義它時,它可以正常工作,但我不知道是否有更好的方法來實現它。 – seaBass

+0

如果你想讓對象自己分配給一個元素,你可以不用變量。我已經添加了第二個片段,告訴你如何完成它。對象知道的唯一東西就是元素。它可以將自己綁定到元素上。正如你所看到的,甚至不需要在變量中存儲引用。 – GolezTrol

+0

@Andrew:這裏的解決方案不是創建HTML並使用內聯事件處理程序,而是使用DOM API和閉包(如有必要)。通過http://www.quirksmode.org/js/introevents.html瞭解更多有關事件處理的信息。下次我建議詢問您正在嘗試解決的實際問題。 –