getElementById("mylink");
addListener(mylink, 'click', foo);
function foo()
{
alert(this.href);
}
You??™d probably expect this to refer to the link, and the href would pop up, but in IE it
doesn??™t. Let??™s take a moment to expand on the this keyword and see how context is handled.
Examining Context
When you run a function, the this keyword belongs to the owner of the function. The default
owner is the window object:
function myfunction()
{
alert(this); // this would refer to the window object.
}
As you add functions onto other objects, you are essentially chaining them together. One
object belongs to another, which belongs to another:
var el = function ()
{
alert(this); // this would refer to the window object.
}
el.methodname = function()
{
alert(this); // this would refer to our el object
}
This tends to get a little confusing when you pass a method of one object as a parameter
into another function:
var el = function ()
{
alert(this); // this would refer to the window object.
}
el.methodname = function()
{
alert(this);
}
CHAPTER 2 n HTML, CSS, AND JAVASCRIPT 46
function myfunc(func)
{
func();
}
myfunc(el.methodname);
The path of execution bounces around, so let??™s step through it:
1. Create an el object and assign it a method called methodname(). If you were to run
el.methodname() now, you??™d get the el object.
2. Create a function called myfunc() that accepts one parameter.
Pages:
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99