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:
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:
/**
* 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();
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
.
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:
var unboundFunction = Person.prototype.sayName;
unboundFunction();
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:
var boundFunction = Person.prototype.sayName.bind(john);
boundFunction();