Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why value of 'this' changes from document to window

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.

like image 681
shriidhar Avatar asked Jun 20 '14 03:06

shriidhar


2 Answers

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
like image 126
Nikhil Talreja Avatar answered Nov 12 '22 03:11

Nikhil Talreja


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);
like image 43
Ja͢ck Avatar answered Nov 12 '22 05:11

Ja͢ck