I know how to use jQuery’s $(this) selector and I also understand the principles of OOP in Javascript. I always accepted that it just works, because somebody else implemented it, but I would love to know why and how it works.
$(function(){
$('.foo').each(function(){
console.log($(this));
});
});
Given this code. I know that $('.foo') finds a set of HTML elements and returns a jQuery object which is able to iterate over them using .each(...). The internal structure of the each() method then probably calls the closure, which has been passed as a parameter.
But why does this then reference the particular HTML element inside the closure? I always thought that this would only reference a new scope, as far as it’s wrapper has been instantiated using new. So wouldn’t it be much more consistent if this referenced window instead?
In the end you can always force a
thisvalue in a function using.callor.apply. jQuery does this; look at the source of.each:Here, the
thisvalue will be set to the element (object[i]), and the counter (i) and the element are passed as arguments to your function, which iscallback.