Kirk’s PRNG

"Anyone who considers arithmetical methods of producing random digits is, of course, in a state of sin." --John von Neumann

« Back to blog

Javascript Function Overwriting

Browser incompatibilities are going to be with us for the foreseeable future. This can lead to lots of ugly and inefficient browser detection branches in javascript functions.

 
function foo(bar) 
{ 
  if(navigator.userAgent.toLowerCase().indexOf('msie') > -1) {
    //do Internet Explorer Stuff 
  } 
  else { 
    //do Firefox Stuff 
  } 
} 

Instead we can take advantage of scoping and first-class functions to rewrite the function during the first execution, allowing each subsequent execution to skip the branching.

 
function foo(bar) 
{ 
  if(navigator.userAgent.toLowerCase().indexOf('msie') > -1) { //if 
Internet Explorer 
    //rewrite foo to only execute the internet explorer code 
    foo = function (bar) { 
      //do Internet Explorer Stuff 
    }; 
  } 
  else { 
    //rewrite foo to only execute the firefox code 
    foo = function(bar) { 
      //do Firefox Stuff 
    }; 
  } 
 
  //after rewriting the function, call it so the original caller 
  //receives what they need 
  return foo(bar); 
} 

 
Got an account with one of these? Login here, or just enter your comment below.
Posterous-login    twitter