这是一个来自“
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’一样保持全球范围?这在内部如何运作?