Callback functions make functions in JavaScriot far more flexiblwe than they would otherwise be.By passing a function into another function as a parameter we make the function it is passed to more flexible in that part of its processing is now determined by the function we pass to it.
In this example we have a generic processArray function that will run our callback function for every single entry in the array. Just what that processing will be is not defined in our processArray function but is instead determined by the function passed into the second argument.Unless we need to be able to call the callback function from elsewhere in our code outside the function we are passing it to we can also simplify our code by just passing it as an anonymous function. For the purpose of the example we pass in an anonymous function that will multiply each of the entries in the array by two. Should we want to change what is to be done with each entry in the array we'd just change the content of the function that we are using as the second parameter.
http://javascript.about.com/od/byexample/a/usingfunctions-callbackfunction-example.htm
var myary = [4, 8, 2, 7, 5];
processArray = function(ary, callback) {
for (var i = ary.length-1; i >= 0; i--)
&nsp; ary[i] = callback(ary[i]);
}
return ary;
}
myary = processArray(myary, function(a) {return a * 2;});
No comments:
Post a Comment