I can address the JavaScript part. Because you can declare anonymous functions in JS (var fn = function(){/* stuff */};
, you can also pass those functions as parameters to other functions. In fact, you've already used lambdas if you've ever had to do a custom sort routine. For example:
// Standard sort:
x = [4,3,6,7,1,5,2];
x.sort();
// Custom sort:
y = [
{'val':4,'name':'four'},
{'val':3,'name':'three'},
{'val':6,'name':'six'},
{'val':7,'name':'seven'},
{'val':1,'name':'one'},
{'val':5,'name':'five'},
{'val':2,'name':'two'},
];
y.sort(function(a,b){ return a.val > b.val ? 1 : -1 });
replace()
is another example that takes lambda functions as parameters.
Doing this in your own code is pretty easy, though in practice I never found a circumstance when this couldn't be done more clearly some other way (if anyone else needs to manager your code, you're guaranteed to break their head until they see the lambda).
Here's an example. Say you have a Widget
object that produces some form of output. You know it will always produce output, but you don't know what form that output will take. One solution is to pass into the object the method it needs to generate that output. Here's a simple implementation:
First, the Widget
itself. Note that Widget.prototype.publish()
takes a single parameter, which is your custom formatter:
var Widget = function() {
var self = this;
var strPrivateVar = "This is a private variable";
self.publicVar = "This is a default public variable";
self.publish = function(f) {
var fnFormatter = f;
var strOutput = "The output is " + fnFormatter(self,strPrivateVar);
return strOutput;
}
};
Next, your formatters. One gives a brief summary while the other gives the full text:
var fnSummary = function(o,s) {
var self = o;
var strPrivateVar = s;
return strPrivateVar.substr(0,5) + ' ' + self.publicVar.substr(0,5);
}
var fnDetails = function(o,s) {
var self = o;
var strPrivateVar = s;
return strPrivateVar + ' ' + self.publicVar;
}
And last, your implementation:
var wWidget = new Widget();
wWidget.publicVar = "I have overridden the public property";
var strSummary = wWidget.publish(fnSummary);
var strDetails = wWidget.publish(fnDetails);
console.log(strSummary,strDetails);
This solution means you don't need to alter the wWidget
object to get the desired output. Due to scoping issues, you do have to jump through some hoops to get the variables from the object into the publisher methods, but once you do that the rest is easy.
I know there are others on SO that could give a better example, but I hope this helps you.