↑
Main Page
this keyword
sayHi.alternate = function() {
alert(“hola”);
};
sayHi(); //outputs “hi”
sayHi.alternate(); //outputs “hola”
Here, the method
alternate()
is actually a method on the function
sayHi
. It is possible to call the
sayHi()
as a regular function to output
“hi”
as well as calling
sayHi.alternate()
to output
“hola”
.
Even so,
alternate()
is considered to be a method of the function
sayHi()
in the public scope, not a
static method.
The this keyword
One of the most important concepts to grasp in ECMAScript 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 instan-
tiating 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”
89
Object Basics
06_579088 ch03.qxd 3/28/05 11:36 AM Page 89
Free JavaScript Editor
Ajax Editor
©
→ R7