In fact, most custom event systems
use callbacks as a way of calling a function when an event occurs.
Callbacks are normally handled by passing a function into another object as one of the
parameters:
function Animation(startFunction, endFunction)
{
startFunction();
/* perform our animation magic here */
endFunction();
}
Animation( function(){ alert('Start!') }, function(){ alert('End!') } );
Two anonymous functions were passed in: the first will get called before the animation
starts; the second will get called after it ends.
CHAPTER 3 n OBJECT-ORIENTED PROGRAMMING 74
Passing in a function that is a method of an object can be problematic unless you know
what to expect. In this case, the method will be disconnected from the object. When the function
is executed from within the other function, you??™ll likely get an error message:
function Pizza(includePepperoni)
{
this.pepperoni = includePepperoni;
this.hasPepperoni = function(){ return this.pepperoni; }
}
var newPizza = new Pizza(true);
function eatPizza( hasIngredient )
{
alert('Has Ingredient? ' + hasIngredient() );
}
eatPizza( newPizza.hasPepperoni );
While this example might seem a little odd, the key thing to note is that the ingredient
returns undefined. The hasPepperoni() method has become detached from the newPizza
object and is being executed in the parent context of the eatPizza() function, which happens
to be the window object and doesn??™t have a hasPepperoni property.
Pages:
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133