Understanding “this” keyword in JavaScript

Whether it is JavaScript or java we have been using “this” in many places. This “this” is quite interesting. “this” is actually a reserved keyword. Although it acts differently in JavaScript than all other languages.
In java we know that “this” refers to the same object in which ”this” resides. But in javascript we will see that it works a little differently. In JavaScript “this” is a variable that is automatically set when a function is invoked. The value it’s given depends on how a function is invoked.In JavaScript we are able to invoke functions In many ways. For each different way behavior of “this” is different.
Whenever a function is called, we must look at the immediate left side of the brackets / parentheses “()”. If on the left side of the parentheses we can see a reference, then the value of “this” passed to the function call is exactly of which that object belongs to, otherwise it is the global object.
If the function is invoked using Function.call() or Function.apply(), “this” will be set to the first argument passed to .call()/.apply(). when the first argument passed to .call()/.apply() is null or undefined, “this” will refer to the global object. The function being invoked was created using Function.bind(), “this” will be the first argument that was passed to .bind() at the time the function was created. If the function is being invoked as a method of an object, this will refer to that object. Otherwise, the function is being invoked as a standalone function not attached to any object, and this will refer to the global object. In the following we will see some examples of the above processes.

// A function invoked using Function.call()
 var foo = {
    bar: function() {
        console.log( "Hi! My name is " + this.myName );
    },
    myName: "name"
};
 var myObject = {
    myName: "name1"
};
 foo.bar();                  
foo.bar.call( myObject );  
// A function created using Function.bind()
var myName = "object";
var sayHello = function() {
    console.log( "Hi! My name is " + this.myName );
};
var nameObject = {
    myName: "name"
};
var nameObjectHello = sayHello.bind( nameObject );
 sayHello();      
nameObjectHello();

In the above example we can see that at time of function.call() “this” refers to the global object. When we are invoking function.bind() “this” is referred to the .bind(). When invoking in method of object, “this” refers to the same object. Let’s look another example.

var o = {prop: 20};
function foo() {
  return this.prop;
}
o.f = foo;
console.log(o.f());

In this example we can see that when prop is returned by “this”. It refers to the object ‘o’. The value of “this” passed to all functions. it is based on the context in which the function is called at run time.


window.foo = 'foo';
window.myObject = {foo: 'I am myObject.foo'};
window.bar = function() { ! console.log(this.foo); };
window.myObject.bar = window.bar;
window.myObject.bar();
window.bar();

Using “this” in a constructor:

When a function is invoked with the “new” keyword, the value of “this” in the constructor refers to the instance itself. If a function is used as a constructor then “this” is bound with the new object. However it is not the only rule and “this” can often refer to a different object. Example as follows:

function func(){
  this.a = 37;
}
var x = new func();
console.log(x.a); // logs 37
function func2(){
  this.a = 37;
  return {a:38};
}
x = new func2();
console.log(x.a);

In the above example the value in return is stored in this.

Using “this” to call and apply:
If a function uses “this” in its body, then the value can be bound with a particular object. An object that can use call or apply method.

function add(c){
  return this.a + this.b + c;
}
var o = {a:1, b:2};
add.call(o, 10); 
add.apply(o, [20]); 

In the above example we can see that in time for calling or applying we are only calling the object which is referred by this. So, “add.call(o, 10); ” in this statement 10 will be added after 1 and 2 has been added. The value of “this” is normally determined from the context in which a function is called, but we can overwrite/control the value of “this” using apply() or call() to define what object this points to when invoking a function.
In nested function “this” keyword refers to the head object. For this predicament we have to be cautious using “this” in nested function. Example as follows:

 var foo = {
  func:function() {
     console.log(this); 
     foo2=function() {
        console.log(this); 
        foo3=function() {
           console.log(this); //logs window, as it’s the head object
        }();
     }();
  }
};
 foo.func();
 

With scope chain we keep a reference to “this” in the parent function. Example as follows:

var foo = {
  myProperty:'prop', 
    func:function() {
    var that=this; 
    var helperFunction function() { 
           console.log(that.myProperty); 
           console.log(this); 
        }();
    }
}
 foo.func(); 

In the above example we had used a variable called ‘that’. ‘that’ store a reference to this in func scope.

If you find this article helpful, you can connect us in Google+ and Twitter.

Enter your email address:Delivered by FeedBurner

3 thoughts on “Understanding “this” keyword in JavaScript

    1. Yes, the above link is really good. I would suggest the author to read the above and if possible – to write his understanding about the above topic. Thanks for the link.

Leave a Reply

Your email address will not be published. Required fields are marked *