Under-estimated javascript

Thursday 27 May 2004This is over 20 years old. Be careful.

I keep re-discovering the same thing about JavaScript: it’s deeper and sturdier than its reputation. Because it is mostly used by HTML gurus, and often for small effects, it is easy to see JavaScript as a simple shallow language for adding just a little bit of code to web pages. But it really is a full-featured powerful functional programming language.

Simon brought it home once more with Executing JavaScript on page load, where he uses closures and functions as first class objects to solve a web page modularity problem:

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      oldonload();
      func();
    }
  }
}

Comments

[gravatar]
I discovered this back when JavaScript was young, and I wrote a Lisp interpreter in it: http://ganley.org/software/jslisp.html. It's really a pretty nice language, except for (then) a sore lack of development tools; I'd be surprised if that void hasn't been filled by now.
[gravatar]
The addLoadEvent thing is nice, and it can be very easily generalised as follows:

function addEvent(obj, evt, func) {
var oldEvt = obj[evt];
if (typeof oldEvt != 'function') {
obj[evt] = func;
} else {
obj[evt] = function() {
oldEvt();
func();
}
}

It's even nicer to have something that refuses to fire the same event twice, no matter how many times you add it, but I seem to be unique in my need for such a function :-)

Add a comment:

Ignore this:
Leave this empty:
Name is required. Either email or web are required. Email won't be displayed and I won't spam you. Your web site won't be indexed by search engines.
Don't put anything here:
Leave this empty:
Comment text is Markdown.