What I want to do is the following :
I have a function that alert something :
myfunction = function(foobar) {
alert(foobar);
};
Now I want to decorate it so that :
decorate = function(callback) {
return function(foobar) {
callback(foobar);
console.log(foobar);
};
};
So then I can write :
myfunction = decorate(myfunction);
And then myfunction will do the normal + log in the console.
How can I make it works with Javascript ?
Yes, you can. And in fact, you have, your implementation works perfectly: Live example | source
I would recommend using function declarations rather than function expressions, though:
And if you want to create a more generic version, look at using
apply(MDN | spec) and theargumentspseudo-array (MDN | spec): Live example | sourceThat version does a couple of things:
Lets you supply the callback as an argument to one central
decoratefunction.Lets you optionally supply a “context” (
thisvalue) to use when calling the callback.Preserves the value of
thiswhen calling both the original and (if you don’t supplycontext) the callback.…which an be handy when decorating object functions (sometimes called methods).