Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does jQuery do some magic with the `this` variable?

jQuery has gotten us used to the following this pattern:

$(selector).each(function () {
     // do something with `this`
     // `this` iterates over the DOM elements inside `$(selector)`
});

According to this Crockford talk (about 15 minutes in) the value of this inside a function that is not called with the new operator is the global object, except for ES5 strict mode in which case it is undefined.

Does jQuery do some magic with this to get it to something other than the global object? Please point to specific lines of the source code.

like image 784
Randomblue Avatar asked Feb 13 '26 15:02

Randomblue


1 Answers

jQuery uses the 100% non-magical Function.call method to call the callback with a specific this.

like image 73
SLaks Avatar answered Feb 15 '26 06:02

SLaks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!