本文介绍了是真的,JavaScript中的每个函数都是一个闭包吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我理解JavaScript中的每个函数都是一个第一类对象,它有一个内部属性[[scope]],它托管函数的自由变量的绑定记录。但是,有两种特殊情况。


  1. Function构造函数创建的函数是否也是一个闭包? Function构造函数创建的函数对象是特殊的,因为它的[[scope]]可能不会引用其外部函数的词法环境,而只引用全局上下文。例如,

      var a = 1; 
    var fn =(function outer(){
    var a = 2;
    var inner = new Function('alert(a);');
    return inner;
    })();
    fn(); // will alert 1,not 2.

    这是不直观的。这也被称为闭包?


  2. 如果内部函数没有任何自由变量,我们可以说在创建内部函数时形成闭包?例如,

      //这是一个仅用于学术研究的无用的情况
    var fn =(function outer {
    var localVar1 = 1,
    localVar2 = 2;
    return function(){};
    })();

    在这种情况下,fn是指作为内部函数创建的空函数对象。它没有自由变量。在这种情况下,我们可以说形成了关闭吗?



解决方案

这可能是不直观的,因为所有其他JavaScript闭包在它们的词汇范围上,但它仍然匹配我们的。在您的示例中, a 是一个自由变量,并在其他作用域中解析为 a $ c> inner / fn 函数被调用。

问。 说是,称为无趣的关闭,我个人说,因为一个外部范围。 p>

I understand that every function in JavaScript is a first-class object and it has an internal property [[scope]] which hosts the binding records of the function's free variables. However, there are two special cases.

  1. Is the function created by Function constructor also a closure? The function object created by Function constructor is special, because its [[scope]] may not refer to the lexical environments of its outer functions, but only the global context. For example,

    var a = 1;
    var fn = (function outer() {
        var a = 2;
        var inner = new Function('alert(a); ');
        return inner;
    })();
    fn(); // will alert 1, not 2.
    

    This is unintuitive. Is this also called closure?

  2. If an inner function doesn't have any free variables, can we say a closure is formed when the inner function is created? For example,

    // This is a useless case only for academic study
    var fn = (function outer() {
        var localVar1 = 1,
            localVar2 = 2;
        return function() {};
    })();
    

    In this case, fn refers to an empty function object which was created as an inner function. It has no free variables. In this case can we say a closure is formed?

解决方案

Yes, it closes over the global scope. That might be unintuitive because all other JavaScript closures close over their lexical scope, but it still matches our definition of a closure. In your example, a is a free variable, and resolves to the a in an other scope when the inner/fn function is called somewhere.

Depends on whom you ask. Some say Yes, others call them "uninteresting closures", personally I say No because they don't reference an outer scope.

这篇关于是真的,JavaScript中的每个函数都是一个闭包吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 11:13