开发者

calling functions with or without braces scope question

In jquery scripts i often see functions called like this:

var somefunction = function(){
  $(this).doseomething()
}

$(someelement).click( somefunction );

Inside somefunction this seams to refer to the the clicked element. If the braces are used to call the function this does not refare to the clicked element.

Personally i don't like it. I like to s开发者_如何转开发ee if something used in my code is a function or not. I prefere to pass this as argument. This is how i done it until now:

var somefunction = function($clickedLink){
  $clickedLink.doseomething()
}

$(someelement).click(function(){ somefunction($(this)) });

Why can i access the refared element if i don't use the braces? And is it a good practice in general to call functions without braces? Does it has an influence on the performance?


It's not the braces, it's that any function used as an event handler, and the way jQuery calls event handlers (same is true in vanilla JavaScript), the context of that function is going to be the element that the event is firing on.

To be a bit clearer on the other point, you're not calling the function without parenthesis, you're passing a reference to the function. For example, this says "here's the function to run when the event happens":

$(someelement).click( somefunction );

The other method you have does the same thing, just with more overhead of an extra anonymous function:

$(someelement).click(function(){ somefunction($(this)); });

The function() { ... } is what you're passing to run (it's an anonymous function, rather than your named one). It's still not until the click event does somefunction actually get called.


You can do it either way, but they're not equivalent, when you pass a function directly, this is the element and the first argument is the event object...which you often need to stop propagation or prevent default behavior correctly.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜