这是一个来自“
Javascript – The Good Parts”的工作示例.
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’的引用复制到’that’吗?即’that’将与’this’一样保持全球范围?这在内部如何运作?
解决方法
这里涉及两个函数:一个是myObject.double,另一个是helper.当你调用myObject.double()时,这引用了myObject.那样=== myObject.稍后,在该函数内部,您还调用了helper(),并且在该范围内,您拥有了===全局对象.