我从这里得到了这个代码: 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吗?
答案 0 :(得分:1)
Function.length
表示函数预期的参数数量,addMethod
表示参数数量为3。 arguments
引用传递给addMethod
的参数数组。
因此,addMethod
函数检查预期的参数数量是否与传递的实际参数数量相匹配。
答案 1 :(得分:0)
arguments
是内置的JavaScript类数组对象,每个function
都隐式拥有。它包含函数的传递参数数组。但是arguments
对象不是数组。它类似于Array,但除了length
之外没有任何Array属性。