Keyword this

In Javascript, the keyword this is sometimes misunderstood. Although its use within the context of Object Oriented Programming (OOP) is clear, Javascript sometimes goes beyond. In this short tutorial, I will present a number of examples to help the reader identify three contexts in which the keyword this is used:

  • Object Oriented Programming
  • Unbound functions
  • Bound functions

Use of this in Object Oriented Programming

The main purpose of this in Javascript is to serve Object Oriented Programming. It is used by the methods of a class to access the properties of a class instance. The following example illustrates this use:

In [1]:
/**
 * Person represents a person that has been given a name
 * @class
 * @param {String} name
 */
function Person(name) {
    this.name = name;
}

/**
 * Say name
 * @method
 */
Person.prototype.sayName =  function() {
    return "My name is " + this.name;
}

var john = new Person("John");
john.sayName();
Out[1]:
'My name is John'

The above snippet defines class Person with a constructor that takes a name and the method sayName() that prints the name by using the keyword this.

Use of this in unbound functions

Things start getting complicated if we take full advantage of Javascript. The following snippet uses the method sayName() to define an unbound function. Within unbound functions, the keyword this is set to the global object. See in the below snippet that the property name is undefined in the global object:

In [2]:
var unboundFunction = Person.prototype.sayName;
unboundFunction();
Out[2]:
'My name is undefined'

Use of this in bound functions

Javascript lets you bind an unbound function to an object. A bound function sets the keyword this to the bound object. Below is an example:

In [3]:
var boundFunction = Person.prototype.sayName.bind(john);
boundFunction();
Out[3]:
'My name is John'