|
Helping ordinary people create extraordinary websites! |
Higher Order Programming in JavaScriptBy Sjoerd Visscher2006-08-18
Generating HTML Using functions as argumentsIf you have generated HTML from arrays before, this code will look familiar: var s=''; We will now create a function prettyTemplate(item) {
To create the reduce method, we can use much of the previous example. We'll extend the array prototype, so all arrays will have the reduce method available: Array.prototype.reduce=function(templateFunction) {
Using a function as return valueThe template function will often be simple: It will just wrap each item in the array with one HTML element. F.e. when creating a table, the template function won't do much more than: function wrap(tag) {
In the first example you can see that you can immediately call the returned function, which results in a somewhat unusual syntax of two argument lists next to eachother. There's another special thing happening here: the returned function referes to the Using functions as objectsIn the last example, an array is converted to a table, each item in the array is wrapped with a var TABLE=wrap('TABLE');var TR=wrap('TR');var TD=wrap('TD');
document.write(TABLE(arr.reduce(TR.after(TD)))); In Javascript functions are objects too, and they can also have methods. So we can extend the function prototype so that the Function.prototype.after=function(g) {
Tutorial Pages: » Introduction » Generating HTML » Using methods as functions » When should you use this? This article is licensed under the Creative Commons |
|