Bonus: Function Length

2710 단어 function
How does a function's length property work?
function makeNinja(name){}
function makeSamurai(name, rank){}
assert( makeNinja.length == 1, "Only expecting a single argument");
assert( makeSamurai.length == 2, "Multiple arguments expected");
We can use it to implement method overloading.
 function addMethod(object, name, fn){ 
   // Save a reference to the old method
   var old = object[ name ]; 

   // Overwrite the method with our new one
   object[ name ] = function(){ 
     // Check the number of incoming arguments,
     // compared to our overloaded function
     if ( fn.length == arguments.length ) 
       // If there was a match, run the function
       return fn.apply( this, arguments );

     // Otherwise, fallback to the old method
     else if ( typeof old === "function" ) 
       return old.apply( this, arguments ); 
   }; 
 } 
How method overloading might work, using the function length property.
 function addMethod(object, name, fn){ 
   // Save a reference to the old method
   var old = object[ name ]; 

   // Overwrite the method with our new one
   object[ name ] = function(){ 
     // Check the number of incoming arguments,
     // compared to our overloaded function
     if ( fn.length == arguments.length ) 
       // If there was a match, run the function
       return fn.apply( this, arguments );

     // Otherwise, fallback to the old method
     else if ( typeof old === "function" ) 
       return old.apply( this, arguments ); 
   }; 
 } 

 function Ninjas(){ 
   var ninjas = [ "Dean Edwards", "Sam Stephenson", "Alex Russell" ]; 
   addMethod(this, "find", function(){ 
     return ninjas; 
   }); 
   addMethod(this, "find", function(name){ 
     var ret = []; 
     for ( var i = 0; i < ninjas.length; i++ ) 
       if ( ninjas[i].indexOf(name) == 0 ) 
         ret.push( ninjas[i] ); 
     return ret; 
   }); 
   addMethod(this, "find", function(first, last){ 
     var ret = []; 
     for ( var i = 0; i < ninjas.length; i++ ) 
       if ( ninjas[i] == (first + " " + last) ) 
         ret.push( ninjas[i] ); 
     return ret; 
   }); 
 } 
  
 var ninjas = new Ninjas(); 
 assert( ninjas.find().length == 3, "Finds all ninjas" ); 
 assert( ninjas.find("Sam").length == 1, "Finds ninjas by first name" ); 
 assert( ninjas.find("Dean", "Edwards").length == 1, "Finds ninjas by first and last name" ); 
 assert( ninjas.find("Alex", "X", "Russell") == null, "Does nothing" ); [/cod
  

좋은 웹페이지 즐겨찾기