Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
94 views
in Technique[技术] by (71.8m points)

Is it true that every function in JavaScript is a closure?

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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Is the function created by Function constructor also a closure?

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.

If an inner function doesn't have any free variables, can we still call it a closure?

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...