5

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.

shriidhar
  • 427
  • 3
  • 15
  • 1
    See: http://stackoverflow.com/questions/13441307/how-does-the-this-keyword-in-javascript-act-within-an-object-literal/13441628#13441628 for a complete (really, I update it often) description of how "this" works in javascript – slebetman Jun 20 '14 at 04:01

4 Answers4

4

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
Nikhil Talreja
  • 2,754
  • 1
  • 14
  • 20
  • That means `this` points to the object the function belongs to and here `handler` belongs to `window` hence it is `window`. So If use strict mode `this` will point to nothing i.e. `undefined`. right? – shriidhar Jun 20 '14 at 04:09
  • @Shree you are right. [see this](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this) – Bhojendra Rauniyar Jun 20 '14 at 04:11
2

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);
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
0

The this keyword refers to the head object in nested functions source: page no. 76 of the book

var myObject = {
 func1: function() {
   console.log(this); // logs myObject
   var func2 = function() {
     console.log(this) // logs window, and will do so from this point on
   var func3 = function() {
     console.log(this); // logs window, as it’s the head object
   }();
   }();
 }
}
myObject.func1();

So, in your case handler function is inside ready function in which this refers to global object i.e. window.

Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231
0

Like this the context will remain:

this.handler = function() {
  console.log(this);       // this = document!!!
}
console.log(this);
this.handler();
HeyMan
  • 1,529
  • 18
  • 32