One reason why Javascript rocks:
As a use case, imagine you want to restrict a certain set of functions to only run if you are logged in. Doing stuff like this is ridiculously easy with first-class functions.
Here’s a generic decoration example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
(function()
{
var original = function(paramOne, paramTwo) {
console.log('original: ' + paramOne + ' ' + paramTwo);
};
var decorator = function(originalFn) {
return function(paramOne, paramTwo) {
console.log('decorator: ' + paramOne + ' ' + paramTwo);
originalFn(paramOne, paramTwo);
};
};
var fnTable = {};
var registerCallback = function(url, callback) {
fnTable[url] = callback;
};
registerCallback('/abc', original);
registerCallback('/def', decorator(original));
fnTable['/abc']('one', 'two');
fnTable['/def']('three', 'four');
})();
|
Update: Here’s the specific way you’d do this with node.js/Express:
Since all of the URL handlers you register have the same signature, it’s easy to add precondition checks to the handlers via decorators.
1
2
3
4
5
6
7
8
9
10
11
12
|
var decorator = function(originalFn) {
return function(req, res) {
if (req.session.userLoggedIn) {
originalFn(req, res);
} else {
redirectSomewhere(res);
}
}
}
app.get('/url', decorator(original));
app.post('/other', decorator(original));
|
You get preconditions essentially for free, which is a damn sight better than adding the if() block to each and every handler function. Also, if you need more preconditions in the future, you can just stack them.