這裏是一個來自「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'相同的全球範圍?這是如何在內部工作的?
+1替代 – sojin 2010-12-06 13:48:16