JavaScript: Why does closure only happen if I assign the return function to a variable?

纵饮孤独 提交于 2021-02-04 09:19:11

问题


Even after reading You don't know JS and JavaScript: The Core I still couldn't understand the behavior of the following code.

Why, when I call counter()(), do I get no closure, but if I assign a variable to the result of counter(), like var getClosure = counter(), I then get a closure when calling getClosure()?

function counter() {

    var _counter = 0;

    function increase() { return _counter++ }

    return increase;
}

// Double ()() to call the returned function always return 0, so no closure. 
counter()() // returns 0
counter()() // returns 0
counter()() // returns 0
counter()() // returns 0

var createClosure = counter();

createClosure() // returns 0
createClosure() // returns 1
createClosure() // returns 2
createClosure() // returns 3

回答1:


_counter is the local variable within function counter(). Every time when you call counter() a new _counter will be created.

But var createClosure = counter() only called the function 1 time, that's why _counter is not newly created every time and 'remembered' there (that's where closure happens)




回答2:


Each time you call counter()(), it creates a new function and a new closure. So the result is always 0.

On the contrary, when var createClosure = counter(); is executed, a function and closure are created and saved in the variable createClosure. Next time when you call createClosure(), the saved one is invoked and the created closure is used. Therefore the results are 0, 1, 2, 3, ...




回答3:


To put in another way, the return value of the counter() function, which is the closure, isn't persisted or rather it is discarded when you simply call the function as is.

However after assigning that return value to var createClosure. You are able to call the closure as many times as needed



来源:https://stackoverflow.com/questions/47342760/javascript-why-does-closure-only-happen-if-i-assign-the-return-function-to-a-va

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!