When actually is a closure created?

后端 未结 5 859
谎友^
谎友^ 2021-02-04 08:37

Is it true that a closure is created in the following cases for foo, but not for bar?

Case 1:



        
5条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-04 09:17

    In none of these examples is a closure created.

    The second would create a closure if you actually created a function and did something with it, now you just create a function and then throw it away. Same as adding a line 3+8;, you create a number, and then throw it away.

    A closure is simply a function which references variables from its creation environment in its body, a canonical example is an adder:

    function createAdder(x) { //this is not a closure
        return function(y) { //this function is the closure however, it closes over the x.
            return y + x;
        }
    } //thus createAdder returns a closure, it's closed over the argument we put into createAdder
    
    var addTwo = createAdder(2);
    
    addTwo(3); //3
    

提交回复
热议问题