开发者

Why does calling a function in jQuery need to be wrapped in a method?

Let's say I have a function:

function myFunction() {
 ...
}

I want to call it from event handler. Why this construction doesn't call my function?

$(开发者_运维技巧window).resize(myFunction());

But this does the trick:

$(window).resize(function(){myFunction()});

What is the difference between these types of calling?


$(window).resize(myFunction());

immediately calls myFunction and passes the return value to resize. Adding parenthesis after a function name/reference calls the function.

On the other hand,

$(window).resize(function(){myFunction()});

passes an anonymous function to resize. myFunction is only called when the outer function is called.

Anonymous functions are nothing special. In this case it is just some kind of inline function definition. You can easily replace it with a function reference:

var handler = function(){myFunction()}; // take out the function definition
$(window).resize(handler);  // and replace it with the new name

Now you can see that there are no parenthesis after the function name, which means, handler is not called, only the reference is passed.

I hope you can also see now that creating a new function in this example is not necessary. You can achieve the same by simply passing a reference to myFunction:

$(window).resize(myFunction);

But both ways have their use cases.

The first example $(window).resize(myFunction()); can still be useful if myFunction returns a function that should be used as event handler:

function myFunction() {
    var handler = function() {};
    return handler;
}

Maybe the handler retuned depends on a parameter passed to myFunction.

Passing an anonymous function is necessary if you want to call myFunction with some specific arguments:

function myFunction(a, b) {
    alert(a + b);
}

$(window).resize(function(){
    myFunction(40, 2);
});

Update:

@T.J. Crowder made an important comment about the event object. Every event handler gets the event object passed as first parameter. If you'd define your function as

function myFunction(event) {
 ...
}

to have (easier) access to it, using an anonymous function, you would have to pass it through:

$(window).resize(function(event){myFunction(event)});

if you want to use it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜