In following code I am not able to understand why the value of this changes to window from document in function handler when I call it from the document context.
$(document).ready(function() {
var handler = function() {
console.log(this); // this = window
}
console.log(this); // this = document
handler();
})
As per my understanding the value of this is determined from its execution context. Now when I am document.ready function this points to document which is expected, but when I call method from that context, why is my context changing to window from document.
Thanks in advance.
Inside a function, the value of this depends on how the function is called.
var handler = function () {
console.log(this); // this = window
};
In this case, the value of this is not set by the call. Since the code is not in strict mode, the value of this must always be an object so it defaults to the global object i.e window.
In the global execution context (outside of any function), this refers to the global object, whether in strict mode or not.
console.log(this); // this = document
Basically, whenever you see a bare function call, i.e. "handler()", JavaScript will call it as if you wrote:
handler.call(null);
This is different from, say, foo.handler() in which case it will run as:
handler.call(foo);
If you want to see document inside your function, you need this:
handler.call(this);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With