2010-12-06 58 views
6

這裏是一個來自「Javascript - 好的部分」的工作示例。JavaScript中的函數調用模式範圍規則

function add(x, y){ return x + y}; 

var myObject = { 
    value: 0, 
    increment: function (inc) { 
     this.value += typeof inc === 'number' ? inc : 1; 
    } 
}; 

myObject.increment(2); 
document.writeln(myObject.value); 

myObject.double = function () { 
    var that = this; // Workaround. 

    var helper = function () { 
     that.value = add(that.value, that.value) 
    }; 

    helper(); // Invoke helper as a function. 
}; 

myObject.double(); 
document.writeln(myObject.value); // 4 

對於函數調用模式,'this'對象將具有全局引用。但我不能完全理解下引擎蓋提到的解決方法的: -

var that = this; // Workaround. 

,如果我們這樣做,我們是不是僅僅複製引用「這個」到「那個」?即'那'將與'this'相同的全球範圍?這是如何在內部工作的?

回答

2

這裏涉及兩個功能:一個是myObject.double,另一個是helper。當你致電myObject.double()這是指myObject。所以that === myObject。稍後,在該功能中,您還可以撥打helper(),並在該範圍內您有this === the global object

10

這不是同樣在這裏,thismyObject所以你得到正確的value財產有,this要提到window ......這就是爲什麼你要保持基準像它這樣做。

You can test it out herehelper函數內部的一些警告顯示發生了什麼很好。

另一種方法是,以.call().apply()與正確的上下文的功能,所以this繼續指向你想要的myObject實例......是這樣的:

myObject.double = function() { 
    var helper = function() { 
     this.value = add(this.value, this.value) 
    }; 
    helper.call(this); // Invoke helper as a function. 
}; 

You can test that version here

+0

+1替代 – sojin 2010-12-06 13:48:16