uwMike.com

I'm in Waterloo at the moment, and next available to work in September 2008.

Javascript Function Overrides

September 9th, 2005

Programming languages vary in power. Paul Graham argues that it’s a mistake to use anything but the most powerful language available. And power is roughly equivalent to level of abstract-ness.

PHP is a very useful language. It’s got associative arrays that completely rock, a tremendous set of functions for string processing, and a truly extraordinary level of online documentation. Besides that, it’s ubiquitous on shared hosts, so it’s a snap to get started.

But PHP is missing certain language structures. I find it curious that it was not Ruby that revealed this to me, but, in fact, Javascript.

Update: What’s described here is not actually “nameless” or “anonymous” functions, but in fact the property of a function being treated as a first-class object that it’s possible to assign to a variable.

Yes, that Javascript

Consider the following Javascript snippet:

var doSomething = function(a, b) {
  ...
  return someValue;
}

Okay, it’s a function that takes two arguments. You pass in two values and you get back a response.

Now, consider a situation where this function is long and complicated, and part of a project that has atomic releases on a periodic schedule.

If you want to modify the functionality of it, you’re going to have to track your changes so that you can update the new version in the same way.

However, consider this bit of Javascript:

var oldSomething = doSomething;

doSomething = function(a, b) {
  ...
  var c = oldSomething(d, e);
  ...
  return someOtherValue;
}

This is extremely significant. The function has been effectively “wrapped”, but under exactly the same name, and without modifying the original source.

PHP cannot do this.

Will I leave PHP behind just because it lacks anonymous functions? Of course not. But as I discover these pieces of missing functionality, I become all the more able to recognize those situations where they would have been useful.

And it gives me all the more reason to continue exploring the world of other languages.

Mike

Leave a Reply

You can use Markdown for style. I love hearing from readers, but please don’t hijack the discussion, use offensive language, or try to sell anything.

© 2004-2008, Mike Purvis, some rights reserved. I'm running Wordpress, and I have an RSS feed.