Programming Tutorials

this keyword sample in Javascript

By: Nicholas C. Zakas in Javascript Tutorials on 2008-08-16  

One of the most important concepts to grasp in JavaScript is the use of the this keyword, which is used in object methods. The this keyword always points to the object that is calling a particular method, for example:

var oCar = new Object;
oCar.color = "red";
oCar.showColor = function () {
alert(this.color); //outputs "red"
};

Here, the this keyword is used in the showColor() method of an object. In this context, this is equal to car, making this code functionality equivalent to the following:

var oCar = new Object;
oCar.color = "red";
oCar.showColor = function () {
alert(oCar.color); //outputs "red"
};

So why use this? Because you can never be sure of the variable name a developer will use when instantiating an object. By using this, it is possible to reuse the same function in any number of different places. Consider the following example:

function showColor() {
alert(this.color);
}
var oCar1 = new Object;
oCar1.color = "red";
oCar1.showColor = showColor;
var oCar2 = new Object;
oCar2.color = "blue";
oCar2.showColor = showColor;
oCar1.showColor(); //outputs "red"
oCar2.showColor(); //outputs "blue"

In this code, the function showColor() is defined first (using this). Then, two objects (oCar1 and oCar2) are created, one with a color property set to "red", and the other with a color property set to "blue". Both objects are assigned a property called showColor that points to the original function named showColor() (note that no naming problem exists because one is a global function and the other is a property of an object). When calling showColor() on each object, the oCar1 outputs "red" whereas oCar2 outputs "blue". This happens because the this keyword in the function is equal to car1 when oCar1.showColor() is called and equal to oCar2 when oCar2.showColor() is called.

Note that the this keyword must be used when referring to properties of an object. For instance, showColor() wouldn't work if it were written like this:

function showColor() {
alert(color);
}

Whenever a variable is referenced without an object or this before it, JavaScript thinks that it is a local or global variable. This function then looks for a local or global variable named color, which it won't find. The result? The function displays "null" in the alert.






Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in Javascript )

Latest Articles (in Javascript)