在使用jQuery的时候,有许多函数可以具有不同个数不同类型的参数。
如fadeIn()、fadeIn("fast")、fadeIn(1000)和css("height")、css("height",100)
咋一看,这类似于Java语言中的重载。但是js作为一种弱类型的语言,实在想不明白是怎样实现这样的重载的。
查了下资料,发现两个要点:arguments和constructor.
arguments 是函数执行时的对象,储存函数执行时传入的参数,类似于数组,但是只可读不可写。
constructor 可以判断某个对象的“构造函数”
所以,在js中,函数的重载可以这样实现:
function test (){
var len = arguments.length;
if(0 == len){
console.log("no argument");
}else if (1 == len){
if (arguments[0].constructor == String) {
console.log("one argument is string");
} else if(arguments[0].constructor == Object){
console.log("one argument is Object");
}
}
}
test(); //no argument
test("aaaa"); //one argument is string
test({"name":"keeva"}); //one argument is Object