zoukankan      html  css  js  c++  java
  • Javascript 中函数的 length 属性

    每个函数都有一个 length属性 (函数名.length), 表示期望接收的函数的个数(而不是实际接收的参数个数)

    它与arguments不同。 arguments.length 是表示函数实际接收的参数个数。

    试想一下 利用这个功能 可以不可以实现根据函数参数个数的重载呢。如何解决正常情况下如果定义重名函数则会把前面的覆盖的问题?

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

    参考:http://ejohn.org/apps/learn/#90

  • 相关阅读:
    工业设计之美
    狠挖用户需求与用户分析——赫志中
    《必然》
    在一周内学会使用 AUTO CAD
    可控硅调光知识总结
    PADS Logic Decal、Layout Decal绘制
    BUCK-BOOST反激变压器设计
    RCC BUCK-BOOST变压器设计
    产品生产
    由《旧制度与大革命》提取的5个感触
  • 原文地址:https://www.cnblogs.com/dubaokun/p/3603833.html
Copyright © 2011-2022 走看看