Jiaaro

…on life, the universe, and everything

Pythonic Decorators in Javascript

I've found plenty of examples of the Class decorator around the internets, but none of the function decorator I've come to know and love in python, so here it is:

x = function(msg) {
 alert(msg);
 return msg;
}
my_decorator = function(fn) {
 var that = this;
 return function() {
   msg = "Message: " + msg;
   return fn.apply(that, arguments);
 }
}
x = my_decorator(x);
x('qwery');

// result: an alert that says, "Message: querty"