Here's my compose function, as a polyfill
Function.prototype.compose = function(prevFunc) {
var nextFunc = this;
return function() {
return nextFunc.call(this, prevFunc.apply(this,arguments));
}
}
These work:
function function1(a){return a + ' do function1 ';}
function function2(b){return b + ' do function2 ';}
function function3(c){return c + ' do function3 ';}
var myFunction = alert(function1).compose(function2).compose(function3);
myFunction('do');
var roundedSqrt = Math.round.compose(Math.sqrt)
roundedSqrt(6);
var squaredDate = alert.compose(roundedSqrt).compose(Date.parse)
quaredDate("January 1, 2014");
But this does not work!
var d = new Date();
var alertMonth = alert.compose(getMonth); <--
alertMonth(d); ^^^^
Error throws error "Uncaught ReferenceError: getMonth is not defined" in google chrome.
Now, if I try either of these instead:
var d = new Date();
function pluckMonth(dateObject) {return dateObject.getMonth();}
var alertMonth = alert.compose(pluckMonth);
var alertMonth2 = alert.compose(function(d){return d.getMonth()});
alertMonth(d);
alertMonth2(d);
They work.
Ok, so, why is that? I don't want to write extra functions, I want it to just work. The compose
function uses the apply
utility and just uses this
for the thisArg
, so it should work for object members as well as stand-alone functions, right??
i.e., these are equivalent
this.method()
method.call.apply(this)