简体   繁体   中英

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?

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.

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.

In the first line the second parameter is a method. And in the second line its a method call.

you could also write it like this

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

$(this).fadeIn(1000, fadeInCallback);

So what we do is that we pass in a reference to the fadeInCallback so the jQuery fadeIn function can call fadeInCallback once it's done with the fading.

The second line will execute

alert('done fading in');

before executeing the jQuery fadeIn function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM