Callbacks, Anonymous Functions, and Context

What is the difference between this code:

$('.percentage_field').change(function() { update_percentage(); }); $('.inspect1').change(function(){ show_hide_targets(); }); 

And this code:

 $('.percentage_field').change( update_percentage ); $('.inspect1').change( show_hide_targets ); 
+4
source share
1 answer

When the callback is fired in response to an event, this inside the function sets the DOM element, which is the event object.

In the first example, an anonymous function gets this target element, but this not redirected to calling the internal function. Instead, the internal function works with this according to how it is called . (Here it is a direct raw call (i.e., not called as a member function), so it works with this , equal to window , in script mode.)

In your second example, the update_percentage and show_hide_targets get this element directly.

Consider an example :

 function sayThis() { alert(this); } someElem.addEventListener("click", function() { sayThis() }); someElem.addEventListener("click", sayThis); someElem.addEventListener("click", function() { sayThis.call(this) }); 

The first will warn window (or undefined in strict mode); the second will warn the element into which the listener was launched. The third listener uses an anonymous function, but it calls an internal function using .call(this) , which translates the original this into an internal function.

+4
source

All Articles