Overriding a JavaScript global function - parseInt
Written by Ian Elliot   
Monday, 20 December 2010
Article Index
Overriding a JavaScript global function - parseInt
The new parseInt
A refinement

Banner

 

Next we need to start the new version of the function which first checks to see if the radix argument is defined or not:

 parseInt = function(n, r){
  if (r === undefined) {

as long as the radix is undefined we need to check the string stored in n and work out what the radix should be.  As the radix should be 10 unless the string starts "0x" all we have to do is strip off any leading spaces and test for "0x":

   n = n.replace(/^s*/, "");
   if (n.substr(0, 2) === "0x") {

Alternatively you could just create a regular expression that does the entire job.  If the if statement find a "0x" the radix is 16 otherwise it is set to 10:

    r = 16;
   }
   else {
    r = 10;
   }
  }

With the radix defined one way or another we can now use the original function to compute the result:

  return tempBase(n, r);
 };
}

This is the end of the entire function which modifies the parseInt function.

To make it easier to see how it all fits together the complete listing is:
updateparseInt=function(){
 if(parseInt("010")===10)return;
var tempBase=parseInt;
parseInt = function(n, r){
  if (r === undefined) {
   n = n.replace(/^s*/, "");
   if (n.substr(0, 2) === "0x") {
    r = 16;
   }
   else {
    r = 10;
   }
  }
  return tempBase(n, r);
 };
}

You can see that after a call to updateparseInt the parseInt function is redefined to be:

parseInt = function(n, r){
if (r === undefined) {
  n = n.replace(/^s*/, "");
  if (n.substr(0, 2) === "0x") {
   r = 16;
  }
  else {
   r = 10;
  }
}
return tempBase(n, r);
};

something you can check by doing:

alert(parseInt);

before and after a call to updateparseInt.

The only question about this redefinition that you might have is how can the new parseInt have access to tempBase which was a local variable in updateparseInt? This is the magic of closure. The new parseInt function has access to the local variables of the function it was defined in - hence it can use tempBase for as long as it needs to.

If you now try:

updateparseInt();
alert(parseInt);
alert(parseInt("0xFF"));    // 255
alert(parseInt("111",2));  //7
alert(parseInt("023"));     //23
alert(parseInt("09"))        //9;

you could see the correct results of all of the forms including the "09" example which returns 0 for the unmodified function in most cases.

Banner

<ASIN:0137054890>

<ASIN:0596517742>

<ASIN:0596805527>

<ASIN:0470684143>



Last Updated ( Tuesday, 21 December 2010 )