In Javascript Patterns by Stoyan Stefanov I read about self defining functions (also called lazy function definition). Last day I was writing an event handler for the mousemove event. For Firefox, Chrome and IE9 I could use the pageX and pageY properties of the event object. Off course, in IE < 8 this did not work, so I had to use e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft. I didn't want to test for this property everytime in the mousemove event handler, for performance reasons. After some time, I realised I had created a self defining function:
var getPageXY = function(e) {
if ("pageX" in e) {
getPageXY = function(e) {
return {"x" : e.pageX, "y" : e.pageY}
};
return getPageXY(e);
} else {
getPageXY = function(e) {
return {
"x" : e.clientX + doc.body.scrollLeft + doc.documentElement.scrollLeft,
"y" : e.clientY + doc.body.scrollTop + doc.documentElement.scrollTop};
};
return getPageXY(e);
}
};
So the first time this function is called (in a mousemove event handler), this function rewrites itself, so the next time it is called, it just does what is has to do.
Comments