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:
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]:
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 functionsThings 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]:
In [3]:
var boundFunction = Person.prototype.sayName.bind(john);
boundFunction();
Out[3]: