Thursday 27 May 2004 — This 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
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: