问题描述
在看着学习爱JavaScript的时候,我挂了为什么这个第二版不能工作。它只是返回'function'。是不是一个闭包不允许有一个变量直接赋值给它?
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]
*/
视频链接
推荐答案
它打印出来,因为函数返回一个函数。
It prints that because the function does return a function.
尝试
ctr()();
您使用的两种形式的函数声明具有几乎完全相同的效果。两者都只是创建一个函数并将其绑定到一个符号。在第二个版本中你真正改变的是所涉及的名称(ctr而不是getCtr)。
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.
这篇关于为什么这个闭包返回函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!