JavaScript function generation

Justin Palmer shows me something I hadn’t seen before: generating functions dynamically by assigning properties to the window object. He applies it to creating shortcuts for the new DOM Builder in Prototype, but it could be applied to any situation where you have a bunch of similar functions with a few small differences between them. Don’t write them all out: just write a template that does different things depending on the method name. You needn’t use the window object either: you can use any object you want to add methods to. This results in more legible code than if you wrote one function that changed its behaviour based on the arguments, and that’s exactly what Justin does here. You get $form({id: 'foo'}) rather than Element('form', {id: 'foo'}).

It’s not quite Ruby’s method_missing, but it does demonstrate that JavaScript can be flexible enough to mimic the programming style of other languages quite nicely.

If you’ve enjoyed this article, you might enjoy my recently published book JavaScript Testing Recipes. It’s full of simple techniques for writing modular, maintainable JavaScript apps in the browser and on the server.