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
182 views
in Technique[技术] by (71.8m points)

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

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
question from:https://stackoverflow.com/questions/47342760/javascript-why-does-closure-only-happen-if-i-assign-the-return-function-to-a-va

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

1 Answer

0 votes
by (71.8m points)

_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)


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

...