Decorated JavaScript

I’ve just read The Decorator Pattern for JavaScript. It’s a beautiful example of precisely how flexible a language like JavaScript is. The technique described allows you to run functions before and/or after any function on any object.

The code is fairly understandable as well. When you set up an object as “Decorated”, it adds before() and after() methods. You pass in the name of the function you want run before and another function. Then the magic kicks in. It takes a copy of the original method, and installs a new method in its place which calls all the before hooks, then the original method and finally any after methods.

The only minor disadvantage is that you can’t inspect or alter the return value in the after method. Otherwise, this piece of code is conceptually very similar to Perl’s Hook::LexWrap (a damned fine tool).

I particularly like the way that you can apply the decorator to either all objects or a particular instance thanks to JavaScript’s lovely prototype based OO.

Yes, I’m sure that Dojo gives you all this too. But this is a nice isolated example.