Why does this closure return function?

萝らか妹 提交于 2019-12-13 03:55:17

问题


While watching Learning to Love JavaScript, I got hung up on why this 2nd version wouldn't work. It just returns 'function'. Is a closure not allowed to have a variable directly assigned to it?

function getCtr() {
    var i = 0;
    return function() {
        console.log(++i);
    }
}
var ctr = getCtr();
ctr();
ctr();
ctr();
/* console
1
2
3
*/
/*--------------------------------------
 *   This doesn't work
 */
var ctr = function() {
    var i = 0;
    return function() {
        console.log(++i);
    }
}
ctr();
ctr();
ctr();
/*   console
 *   => [Function]
 */

Video Link http://youtu.be/seX7jYI96GE?t=11m12s


回答1:


It prints that because the function does return a function.

Try

ctr()();

The two forms of function declaration you used have almost exactly the same effect. Both simply create a function and bind it to a symbol. All you really changed in the second version is the name involved ("ctr" instead of "getCtr").

That is, if your test had been like the first setup:

var actualCtr = ctr();

actualCtr();
actualCtr();
actualCtr();

you'll see that it really is the same.




回答2:


In your first version, you define a function getCtr. Then you invoke getCtr, keeping the result as ctr. Then you invoke ctr repeatedly. You are calling the result of calling a function.

In the second version, you define ctr as your first function, then you invoke it repeatedly. You aren't invoking the result of invoking the function.

Here's a version of your second code that works:

var ctr = (function() {
        var i = 0;
        return function() {
            console.log(++i);
        }
    })();
ctr();
ctr();
ctr();


来源:https://stackoverflow.com/questions/11529448/why-does-this-closure-return-function

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