Yes, you can. And actually, you have, your implementation works just fine: Live example | a source
var myfunction = function(foobar) { alert(foobar); }; var decorate = function(callback) { return function(foobar) { callback(foobar); console.log(foobar); }; }; var result = decorate(myfunction); result("Hi there");
I would recommend using function declarations rather than function expressions, though:
function myfunction(foobar) { alert(foobar); } function decorate(callback) { return function(foobar) { callback(foobar); console.log(foobar); }; } var result = decorate(myfunction); result("Hi there");
And if you want to create a more general version, look at apply
( MDN | spec ) and the arguments
pseudo-array ( MDN | spec ): Live example | a source
function decorate(original, wrapper, context) { return function() { try { original.apply(this, arguments); } catch (e) { } try { wrapper.apply(context || this, arguments); } catch (e) { } }; } function myFunction(arg1, arg2) { alert("arg1 = " + arg1 + ", arg2 = " + arg2); } var newFunction = decorate(myFunction, function(arg1, arg2) { console.log("arg1 = " + arg1 + ", arg2 = " + arg2); }); newFunction(1, 2);
There are several things in this version:
Allows you to include a callback as an argument to one central decorate
function.
Allows you to specify a "context" ( this
value) that will be used when calling the callback.
Saves the value of this
when calling both the original and (if you do not supply context
) a callback.
... which is convenient for decorating objects (sometimes called methods).
source share