Why this doesn't fire:
var counter = function () {
return function() {
alert('Fire!');
}
}
counter();
but this does:
var counter = function () {
return function() {
alert('Fire!');
}
}
var test = counter();
test();
It seems like assigning function to a variable makes difference but why?
-
1You need to call the function after creating it. as you are doing in second code.Code Lღver– Code Lღver2013年03月01日 07:06:55 +00:00Commented Mar 1, 2013 at 7:06
-
This is not really a closure issue. It's just an issue of using a function object.Ted Hopp– Ted Hopp2013年03月01日 07:22:07 +00:00Commented Mar 1, 2013 at 7:22
6 Answers 6
Try calling the function returned
counter()();
Comments
You are returning a function. You have to call it also.
Comments
count() returns a function. It does fire, it just doesn't call the function that it returns. In the second example, you are returning the inner function, then firing it via test(). If you want the examples to be similar, change test = count() to test = counter.
Comments
Ok with your first example, you are assigning
function() {
alert('Fire!');
}
to the variable. But aren't asking for it's value. In your second example, you assign the function to the variable as above, then you call are calling it.
Comments
var counter = function () {
alert('Fire!');
}
counter();
This would fire
1 Comment
counter()(), the alert would be fired.In your code
var counter = function () {
return function() {
alert('Fire!');
}
}
counter();
you are simple getting a function in return of counter(). It is like calling a function which returns a value and you are not catching it.
You have to catch the return function and then call it as you have done it in second code.