javascript - calling functions with or without braces scope question -
in jquery scripts see functions called this:
var somefunction = function(){ $(this).doseomething() } $(someelement).click( somefunction ); inside somefunction this seams refer the clicked element. if braces used call function this not refare clicked element.
personally don't it. see if used in code function or not. prefere pass this argument. how done until now:
var somefunction = function($clickedlink){ $clickedlink.doseomething() } $(someelement).click(function(){ somefunction($(this)) }); why can access refared element if don't use braces? , practice in general call functions without braces? has influence on performance?
it's not braces, it's function used event handler, , way jquery calls event handlers (same true in vanilla javascript), context of function going element event firing on.
to bit clearer on other point, you're not calling function without parenthesis, you're passing reference function. example, says "here's function run when event happens":
$(someelement).click( somefunction ); the other method have same thing, more overhead of anonymous function:
$(someelement).click(function(){ somefunction($(this)); }); the function() { ... } you're passing run (it's anonymous function, rather named one). it's still not until click event somefunction called.
you can either way, they're not equivalent, when pass function directly, this element , first argument event object...which need stop propagation or prevent default behavior correctly.
Comments
Post a Comment