this keyword in JavaScript

this keyword in JavaScript is important concept, which is  used in object methods. The this keyword is used to call a particular method, for example:

var oCar = new Object;
oCar.color = “red”;
oCar.showColor = function () {
    alert(this.color); //output is “red”
};

 

Here, the this  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 keyword in JavaScript, 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”

 

 

Leave a Reply