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
);
When a callback runs in response to an event,
thisinside the function is set to the DOM element that is the target of the event.In your first example, the anonymous function gets the
thisof the target element, but thatthisis not forwarded to the inner function call. Instead, the inner function runs with athisaccording to how it is invoked. (Here, it’s a direct “raw” call (i.e., not called as a member function), so it runs with athisequal towindow, in non-script mode.)In your second example, the functions
update_percentageandshow_hide_targetsget thethisof the target element directly.Consider an example:
The first will alert
window(orundefinedin 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 originalthisto the inner function.