The placeOrder function allows the user to place an order, passing in the items in the order as a set of arguments. Different people can supply different arguments to build their own personal orders.
function placeOrder() {
if (arguments.length == 0)
alert("Nothing for me, thanks");
else
alert("I'd like " + Array.prototype.join.call(arguments, " and ") + " please");
}
placeOrder("popadums", "chutney", "pilau rice", "chicken Madras", "a pint of lager");
I always order popadums and chutney, whatever else I have. Here's my own version of the function.
function myPlaceOrder() {
if (arguments.length == 0)
alert("Just the popadums and chutney today please");
else
alert("I'd like popadums and chutney and " +
Array.prototype.join.call(arguments, " and ") +
" please");
}
myPlaceOrder("pilau rice", "chicken Madras", "a pint of lager");
Well, that's great for me! The problem is my friends have different items that they always order and we don't want to create lots of similar functions from scratch, one for each person.
I want to be able to create functions based on existing functions but with some arguments already filled in. Here's a preFill method that can be used with any function.
Function.prototype.preFill = function() {
var fn = this;
var args = Array.prototype.slice.call(arguments);
return function() {
return fn.apply(fn, args.concat(Array.prototype.slice.call(arguments)));
};
}
function placeOrder() {
if (arguments.length == 0)
alert("Nothing for me, thanks");
else
alert("I'd like " + Array.prototype.join.call(arguments, " and ") + " please");
}
var myPlaceOrder = placeOrder.preFill("popadums", "chutney");
myPlaceOrder("pilau rice", "chicken Madras", "a pint of lager");
var noPreOrder = placeOrder.preFill();
noPreOrder("popadums", "a pint of lager");
noPreOrder();
Why not attach the pre-filled versions of the function to the function itself? No more searching for the menu!
Function.prototype.preFill = function() {
var fn = this;
var args = Array.prototype.slice.call(arguments);
return function() {
return fn.apply(fn, args.concat(Array.prototype.slice.call(arguments)));
};
}
function placeOrder() {
if (arguments.length == 0)
alert("Nothing for me, thanks");
else
alert("I'd like " + Array.prototype.join.call(arguments, " and ") + " please");
}
placeOrder.Bob = placeOrder.preFill("pilau rice", "a lemonade");
placeOrder.Betty = placeOrder.preFill("a pint of lager");
placeOrder.Bob("chicken korma");
placeOrder.Betty("lamb vindaloo", "a garlic naan");