I have been reading up on the intricacies of ‘this’ in JavaScript. Given this code:
$(document).ready(function() {
console.dir(this);
(function foo() {
console.dir(this);
})();
});
In Chrome, the console shows the first ‘this’ as an ‘HTMLDocument’ (as I expected), but the second ‘this’ is ‘undefined’. Can someone point me to a good explanation of why?
They way in which a javascript function is invoked changes the meaning of
thisinside of it. Here you’ve invoked a method which isn’t associated with any object hence it has nothisvalue to bind to.In the first case the callback is being invoked via JQuery and they are manipulating the callback such that
thispoints to thedocumentDOM element. It’s easy to visualize this as your callback being invoked with applyYou can fix the second version like so
Or another way using
apply