zoukankan      html  css  js  c++  java
  • js实现函数重载

    js本身由于其并不检查参数的个数和类型,而是直接把参数放到一个arguments的对象中,由于这种机制我们并不能像c++和java一样去实现函数重载,而要在函数里面去判断参数的个数和类型来间接实现函数重载

    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; 
      }); 
    } 

    /*Test*/
    ninjas = new Ninjas()
    ninjas.find(); //["Dean Edwards", "Sam Stephenson", "Alex Russell"]
    ninjas.find("Sam");//["Sam Stephenson"]
  • 相关阅读:
    Mysql多实例配置
    Mysql多实例主从复制
    粪发涂墙-321
    粪发涂墙-123
    SpringCloud-粪发涂墙90
    线上BUG定位神器(阿尔萨斯)-Arthas2019-0801
    confluence-工具安装
    新应用启动之类冲突-2019-7-26
    新项目组之应用启动-2019-07-25
    新装虚拟机-2019-07-24日记
  • 原文地址:https://www.cnblogs.com/kinthon/p/5008309.html
Copyright © 2011-2022 走看看