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
It prints that because the function does return a function.
Try
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:
you’ll see that it really is the same.