Reputation: 3271
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?
Upvotes: 1
Views: 78
Reputation: 802
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.
Upvotes: 0
Reputation: 4021
var counter = function () {
alert('Fire!');
}
counter();
This would fire
Upvotes: 0
Reputation: 3936
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.
Upvotes: 0
Reputation: 191729
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
.
Upvotes: 2