Reputation: 1731
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
Upvotes: 0
Views: 81
Reputation: 413712
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.
Upvotes: 4
Reputation: 375564
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();
Upvotes: 1