Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to declare a new (anonymous)function in javascript?

I'm a bit confused in how functions operate in javascript. I understand that they're all objects but how does that change how I would use them as arguments?

For instance, if I'm trying to use a callback function where the 2nd argument is evaluated after 1000ms...

$(this).fadeIn(1000,function(){alert('done fading in');});

Why can't I achieve the same effect with:

$(this).fadeIn(1000,alert('done fading in'));

If I do, it evaluates both at the same time. That is, (this) element fades in and the alert pops up at the same time.

When I'm calling alert(arg), aren't I creating a new object which gets passed into fadeIn()?

How exactly does this work?

like image 873
randomafk Avatar asked Jan 03 '12 08:01

randomafk


2 Answers

In this

 $(this).fadeIn(1000,alert('done fading in'));

what does fadeIn() see as its second argument? It's the result of calling

 alert('done fading in')

we are making the call to alert() before calling fadeIn().

In this case

$(this).fadeIn(1000,function(){alert('done fading in');});

we have an object

 function(){alert('done fading in');}

which fadeIn() calls at the right time.

like image 74
djna Avatar answered Sep 20 '22 03:09

djna


When you write:

$(this).fadeIn(1000,alert('done fading in'));

you call function called alert immadiately by putting function name and parentheses after this name. And to fadeIn the result of this call is passed - this is undefined, because alert returns always undefined.

When you write

$(this).fadeIn(1000,function(){alert('done fading in');});

you create a function object that and pass this function object to fadeIn. So after fadeIn is done it can call this function.

It is the same as:

// create function
var callback = function () { alert('done fading in'); };
// and pass this function to fadeIn
$(this).fadeIn(1000, callback);

but when you write:

var callback = alert('done fading in');
$(this).fadeIn(1000, callback);

then you will call alert immadiately and pass to fadeIn value which alert returns - undefined.

like image 32
Mateusz W Avatar answered Sep 23 '22 03:09

Mateusz W