Categories
Uncategorized

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.

3 replies on “Decorated JavaScript”

I didn’t meant to trackback spam you. That was just me editing the article. I didn’t know typo would send you a trackback every time I saved. Sorry, man.

Leave a Reply to beppu Cancel reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s