简体   繁体   中英

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
);

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 (ie, 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM