I’m just curious to know how jQuery is able to hijack the ‘this’ keyword in Javascript. From the book I’m reading: “Javascript the Definitive Guide” it states that “this” is a keyword and you cannot alter it like you can with an identifier.
Now, say you are in your own object constructor and you make a call to some jQuery code, how is it able to hijack this from you?
function MyObject(){
// At this point "this" is referring to this object
$("div").each(function(){
// Now this refers to the currently matched div
});
}
My only guess would be that since you are providing a callback to the jQuery each() function, you are now working with a closure that has the jQuery scope chain, and not your own object’s scope chain. Is this on the right track?
thanks
You can change the context of a function (i.e. the
thisvalue) by calling it with.call()or.apply()and passing your intended context as the first argument.E.g.
Note: passing
nullto eithercallorapplymakes the context theglobalobject, or, in most cases,window.It’s probably worth noting the difference between
.apply()and.call(). The former allows you to pass a bunch of arguments to the function it’s being applied to as an array, while the latter lets you just add them as regular arguments after the context argument:From the jQuery source: