JavaScript中的函数调用模式作用域规则

这是一个来自“ 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(),并且在该范围内,您拥有了===全局对象.

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...