What does ‘this’ mean inside my JavaScript function

August 1st, 2010 by JorisO | Filed under JavaScript.

In JavaScript the behavior of the ‘this‘ keyword inside a closure created by a function/method can be confusing at times. But ‘this’ doesn’t have to be a real problem. The rules that govern what ‘this‘ denotes inside a function call are actually few and simple. There’s only a few different situations that need to be understood to know this.
this

Option 1 : this is inside a method:

When a function is part of an object and called as such it is also referred to as method.
As would be expected ‘this‘ then refers to the object containing the method.

var obj = {
  showThis:function(){
    console.log(this);
  }
}
obj.showThis();  //will output the obj object;

Option 2 : this is inside a function:

When a function is not invoked as part of an user defined object the ‘this’ keyword is bound to the global object. Even if the function definition happens inside another object or function the ‘this’ keyword will still refer to the global object. If we want to use the inner function to refer to the same ‘this’ that the containing function uses, this must be assigned to another variable inside that both inner and containing function have access to:

var obj = {
  showThis:function(){
    console.log(this);
  }
}

obj.containing = function(){
  var that = this;
  var innerFunction = function(){
    that.showThis();
  }
  innerFunction(); // outputs
 }

obj.containing();  // outputs obj;

Option 3 : this is inside a constructor

When the ‘new‘ keyword is used to call a function, a new object is created with a link to the prototype property. The ‘this’ keyword will now refer to this newly created object.

var Obj = function(mode){
  this.mode = mode;
  this.color = 'green';
}
Obj.prototype.setColor = function(color){
  this.color = color;
  console.log(this)
}
var obj = new Obj('bleh').setColor('purple');  // outputs the obj as instance or copy of Obj, but with properties color as purple and mode set to 'bleh'.

Option 4 : this is inside a function called with the ‘apply‘ method

The apply method of the Function object allows us to specify the meaning of the this keyword inside a function call ourselves. The first argument of apply is the object that ‘this’ will refers to inside the function body and the second (optional) argument is an array of arguments to that function.

An example of this can be found here :
http://www.hardcode.nl/archives_139/article_514-supplying-context-to-handler-lookup-table-in-jquery.htm

Tags: ,


Leave a Reply