/
** KOverLoad
一个创建重载函数的辅助方法。
补充上次的函数。
@Author ake 2010-07-03
@weblog
http://www.cnblog
s.com/akecn
*/
var KOverLoad = function(scop
E) { thi
s.scope = scope || window; //默认添加方法到
这个对象中。同时添加的方法的this指向该对象。
thi
s.list =
{}; //存放重载函数的地方。
return this;
};
KOverLoad.prototype =
{ //添加一个重载的方法。
//@param arg<Function> 重载的方法。
add:function(arg,types)
{ if(typeof arg == "function")
{ var types = (types || []).join(","
); thi
s.list[arg.length + types] = arg; //以参数数量和类型做标识存储重载方法。很显然如果
你的重载
方法参数数量
return this;
}
},
checkTypes: function(types)
{ var type = [];
//console.log(typeof typ
E); []方式创建的数组,其typeof类型为ob
ject
//如果需要判断类型的话 还是用Ob
ject.prototype.to
String.call(typ
E) == "[ob
ject Array]"来判断吧。
for(var i
=0,it; it = types[i++];)
{ type.push(typeof it
); }
return type.join(","
); },
//添加完所有的重载函数以后,调用该方法来创建重载函数。
//@param fc<
String> 重载函数的方法名。
load:function(f
C) { var self = this,args,len,types;
thi
s.scope[fc] = function()
{ //将指定作用域的指定方法 设为重载函数。
args = Array.prototype.slice.call(arguments
); //将参数转换为数组。
len = arg
s.length;
types = self.
checkTypes(args
); //console.log(self.list
); if(self.list[len + types])
{ //根据参数数量调用符合的重载方法。
self.list[len + types].apply(self.scope,args
); //这里指定了作用域和参数。
}else if(self.list[len])
{ self.list[len].apply(self.scope,args)
}else
{ throw new Error("undefined overload type"
); }
}
}
};
var s =
{};
new KOverLoad(s) //设置方法绑定的位置。命名空间?
.add(function(a)
{ console.log("one",a,this)
},["
String"])
.add(function(a,b)
{ console.log("two",b,["
String","
String"])
.add(function(a,
C) { console.log("three",c,"
number",d)
{ console.log("four",d,this)
})
.load("func"
); //在这里的参数就是要创建的重载函数的方法名称。
s.func("a","b"
);