Javascript `this`

What is `this` in javascript?

We’ve talked about scopes and closures, this points to the current scope object. In client side the highest scope is window and in node.js the highest scope is the global objects.

Javascript is a pretty free language. You can either code in functional programming style or object oriented programming style. With functional programming you pass variables and callbacks around. this is quite useless. However with OOP this is a must.

Because this is a node.js tutorial, I’m not going to talk about how this works in the browser. As we mentioned scopes and closures, let’s look at the the following example

var something, another;

something = {

  x : 'x',

  print : function( callback ){
    callback && callback.call( this );
    console.log( this.x );
  }
};

another = {

  x : 'a',

  set_x : function(){
    this.x = 'b';
  }
};

// situation a
something.print( function(){
  another.set_x();
});

// situation b
something.print( another.set_x );

// situation c
something.print( function(){
  another.set_x.call( this );
});
Result
x
b
b

So why in situation b we can set the x of something from another? Because we use call in print from something. What it does is to make the callback shares the same scope with something. In situation a we pass an anonymous function and in the anonymous function we call another.set_x. Because a function creates a different scope, therefore this in print points to the anonymous function not another. To fix it we can use call again just like situation c to make another the same scope with the anonymous callback.


Common mistake

There is one common mistake that people often made is we want to use this in different scope to point to the same object. However the property and method this points to is undefined. To fix it we have to save the higher scope this to a variable say self and then we can use self to do the job for us.

var example = {

  name : 'who',

  wrong : function(){
    setTimeout( function(){
      console.log( this.name );
    }, 0 );
  },

  right : function(){
    var self = this;

    setTimeout( function(){
      console.log( self.name );
    }, 0 );
  }
};

example.wrong();
example.right();
Result
undefined
who

You can read this post Javascript call and apply to understand more about it.


Related posts