4

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
);
Dimitris Leventeas
  • 1,502
  • 2
  • 15
  • 28

1 Answers1

4

When a callback runs in response to an event, this inside the function is set to the DOM element that is the target of the event.

In your first example, the anonymous function gets the this of the target element, but that this is not forwarded to the inner function call. Instead, the inner function runs with a this according to how it is invoked. (Here, it's a direct "raw" call (i.e., not called as a member function), so it runs with a this equal to window, in non-script mode.)

In your second example, the functions update_percentage and show_hide_targets get the this of the target 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 alert window (or undefined in strict mode); the second will alert the element the listener fired on. The third listener uses an anonymous function, but it invokes the inner function using .call(this), which forwards the original this to the inner function.

Community
  • 1
  • 1
apsillers
  • 101,930
  • 15
  • 206
  • 224