微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

原文地址:https://www.jb51.cc/js/150954.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐