SEARCH
0-9 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
Prev | Current Page 122 | Next

Jonathan Snook, Aaron Gustafson, Stuart Langridge, and Dan Webb

"Accelerated DOM Scripting with Ajax, APIs, and Libraries"


You can use the JavaScript function call() to run the function in the context of another
object. In this case, call executes the function hasIngredient, which is the function
hasPepperoni() that was passed in, and then runs it in the context of the pizza, which is the
newPizza object that was passed in. Thus, it behaves just like newPizza.hasPepperoni(). The
this keyword within the hasPepperoni function now properly tells you whether there is pepperoni
on this pizza.
function eatPizza( hasIngredient, pizza )
{
alert('Has Ingredient? ' + hasIngredient.call(pizza) );
}
eatPizza(newPizza.hasPepperoni, newPizza );
Alternatively, you can make use of closures to pass the information in by using your original
function:
function eatPizza( hasIngredient )
{
alert('Has Ingredient? ' + hasIngredient() );
}
eatPizza( function(){ return newPizza.hasPepperoni() } );
An anonymous function was passed in that simply returns whether the value is true or
false. As you??™ve no doubt discovered, there??™s almost always more than one way to accomplish
the same thing.
CHAPTER 3 n OBJECT-ORIENTED PROGRAMMING 75
The Functions call and apply
As you just saw, you can use call to run a function as if it were attached to a particular object.
You can also specify any number of additional parameters that should be passed on to the
function:
hasIngredient.call(pizza, 'hot');
This behaves the same as if you did the following:
newPizza.


Pages:
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
druga wojna światowa Free English grammar and study guid hotel jelenia góra Russian bride counter strike 1.6