2013-05-28 38 views
4

我在一個新的代碼庫中遇到過很多次,我在看,並且想知道是否有任何正確的推理呢?聲明var的原因是什麼= this;在JavaScript?

+1

相關:http://stackoverflow.com/questions/7234282/what-is-the-reason-for-var-this-this?rq=1 – Niko

+0

取代碼,並嘗試用'this'替換'that'在哪裏使用,你會發現它可能不起作用。 – 2013-05-28 14:26:27

+0

http://stackoverflow.com/a/4886696/1651233 – BobTheBuilder

回答

2

您可以使用var that = this;是爲了保持對當前this對象的引用,當後面this會指向別的東西。

實施例(taken from here):

$('#element').click(function(){ 
    // this is a reference to the element clicked on 

    var that = this; 

    $('.elements').each(function(){ 
     // this is a reference to the current element in the loop 
     // that is still a reference to the element clicked on 
    }); 
}); 
+1

與我的答案相同,但有一個例子,發揮得很好:) – ChrisCM

1

有時JavaScript中的this的含義根據範圍而改變。 this裏面的構造函數意味着不同於this裏面的函數。這是關於它的good article

0

如果您想訪問特定函數調用範圍之外/之內的「this」,其中「this」可能已更改。我只能想到一個例子。

相關問題