Defining Functions to be Passed Around as Arguments
Alright, so I've been looking at functions and using them as arguments. Let's say I have a function that takes a function and does it:
function run(someFunction,someArgument) {
someFunction(someArgument);
}
I see that I can pass an existing function, say:
function foo(bar) {
// foo that bar!
}
By calling run(foo,bar);
I can also make up a function in an object on the fly and run it:
var whiteBoy = {
playThat: function(funkyMusic) {
// funk out in every way
}
};
And then I call run(whiteBoy.playThat,funkyMusic);
What I'd l开发者_开发百科ike to be able to do is define a function in the call, like this:
run(/* define a new function */,relevantArgument);
How would I go about doing that?
Like this:
run(function(funkyMusic) {
// funk out in every way
}, relevantArgument);
You were very close when you wrote this:
var whiteBoy = {
playThat: function(funkyMusic) {
// funk out in every way
}
};
What you did there was define a function and assign it to the playThat
property - the only change that I made was to define a function and pass it as an argument instead of assigning it to something.
run(function(when)
{
alert("play that funky music " + when);
},
"noooow!");
精彩评论