getElementById('main');
element.onclick = function(){ element.innerHTML = 'Surprise!'; };
}
CHAPTER 3 n OBJECT-ORIENTED PROGRAMMING 69
The function that you attach to the onclick event creates a closure, so it still has access to
the element variable.
As functions get passed around, they always retain access to this initial scoping. The
function can be returned or set as a parameter to another function, and it still has access to
its original scope. It??™s important to remember, though, that the function has to be declared
from within the function whose variables that you want to retain access to.
function onclickHandler(){
element.innerHTML = 'Surprise!';
}
function attachBehavior(){
var element = document.getElementById('main');
element.onclick = onclickHandler;
}
If you run the attachBehavior function and click your main element, you??™ll get an error
about the element being undefined because the function was declared outside of the
attachBehavior function. Even though it??™s being assigned to a variable from within the function,
where the function gets declared is what matters.
Closures can be useful for referencing information across the divide of event handling,
instead of having to worry about retaining proper access to this:
function launcher(element, message)
{
function openWin()
{
alert(message);
}
addListener(element, 'click', openWin);
}
launcher( document.
Pages:
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127