使用函数长度进行方法重载

时间:2013-12-19 07:40:36

标签: javascript

我从这里得到了这个代码: http://ejohn.org/apps/learn/#90

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

我理解1)函数长度是定义中参数的长度,2)参数是指外部函数的变量数组。

但是参数在addMethod()中引用了什么?我认为它是0,addMethod不起作用。但它的确有效。你能帮我理解addMethod吗?

2 个答案:

答案 0 :(得分:1)

Function.length表示函数预期的参数数量,addMethod表示参数数量为3。 arguments引用传递给addMethod的参数数组。

因此,addMethod函数检查预期的参数数量是否与传递的实际参数数量相匹配。

  1. 如果匹配,则只执行第三个参数(预期为函数)。
  2. 否则,它按第二个参数引用的名称执行该功能。

答案 1 :(得分:0)

arguments是内置的JavaScript类数组对象,每个function都隐式拥有。它包含函数的传递参数数组。但是arguments对象不是数组。它类似于Array,但除了length之外没有任何Array属性。