I just want a thorough explanation for what is happening any why did it work $(this)
.
Here you go.
Functions in JavaScript are called in a context. They are, in fact, standalone and only loosely coupled to the objects they belong to. It is perfectly possible to call a function that "belongs" to to object B in the context of object A, as confusing as it might be at first.
The this
keyword transports the context for the function call. It contains the object the function has been called on.
function test() {
alert(this);
}
// when called in a browser, this will alert "DOMWindow"
When no special context is given, the global context (in form of the window
object, when it comes to JavaScript in a browser) is the default.
var x = [1, 2, 3, 4];
function test2() {
alert(this.push);
}
// this will alert "undefined"
// (as there is no "push" property on the window object)
But as I said, you can change the context a function is called in. The function that does that is aptly named call()
and accepts a parameter that determines the meaning of this
in the function body:
test2.call(x);
// this will alert "function push() { [native code] }"
// (as the "push" property on x happens to be a function)
Now, this is very useful and jQuery does it a lot:
$(".test"); // returns an array of elements of CSS class "test"
$(".test").click( // binds a callback for the "click" event on all of them
function () {
// note how there is no context given for the callback function
alert(this);
}
);
When the click event occurs, the callback function you gave is invoked by jQuery like this
callback.call(affectedDOMElement)
And, magically, the this
keyword has a useful meaning in the callback function body.