hasPepperoni('hot');
The apply function works almost the same way, but instead of specifying each parameter
separately, you can pass in an array as the second parameter, and each of those parameters is
passed through to the function in the same order as specified in the array:
hasIngredient.apply(pizza, ['hot','medium','mild']);
This behaves the same as if you did the following:
newPizza.hasPepperoni('hot','medium','mild');
The Prototype JavaScript library has probably one of the most applicable applications of
the apply function. It extends the Function prototype so every function can automatically be
bound to an object with a very succinct syntax:
Function.prototype.bind = function() {
var __method = this, args = $A(arguments), object = args.shift();
return function() {
return __method.apply(object, args.concat($A(arguments)));
}
}
The $A function is a Prototype JavaScript library function that takes a collection and turns
it into an array by iterating over the collection and adding each element into the array. It then
uses the array method shift to knock off the first element in the array and save it. This is the
first parameter you pass into the function and is the object with which you want to bind. Next,
it returns an anonymous function that does the fun stuff. Through the closure, it takes the current
function, which was assigned to __method, and applies it to object. It then takes the
arguments from before and adds them to the current list of arguments.
Pages:
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135