添加JavaScript重载函数的辅助方法2


代码依然简单。所以依然没什么好解释的。。
复制代码 代码如下:

/** KOverLoad
一个创建重载函数的辅助方法。
补充上次的函数。
@Author ake 2010-07-03
@weblog http://www.cnblogs.com/akecn
*/
var KOverLoad = function(scope) {
this.scope = scope || window; //默认添加方法到这个对象中。同时添加的方法的this指向该对象。
this.list = {}; //存放重载函数的地方。
return this;
};
KOverLoad.prototype = {
//添加一个重载的方法。
//@param arg<Function> 重载的方法。
add:function(arg, types) {
if(typeof arg == "function") {
var types = (types || []).join(",");
this.list[arg.length + types] = arg; //以参数数量和类型做标识存储重载方法。很显然如果你的重载方法参数数量
return this;
}
},
checkTypes: function(types) {
var type = [];
//console.log(typeof type); []方式创建的数组,其typeof类型为object
//如果需要判断类型的话 还是用Object.prototype.toString.call(type) == "[object Array]"来判断吧。
for(var i=0, it; it = types[i++];) {
type.push(typeof it);
}
return type.join(",");
},
//添加完所有的重载函数以后,调用该方法来创建重载函数。
//@param fc<String> 重载函数的方法名。
load:function(fc) {
var self = this, args, len, types;
this.scope[fc] = function() { //将指定作用域的指定方法 设为重载函数。
args = Array.prototype.slice.call(arguments); //将参数转换为数组。
len = args.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",a,b,this)
},["string","string"])
.add(function(a,b,c) {
console.log("three",a,b,c,this)
},["string", "number", "string"])
.add(function(a,b,c,d) {
console.log("four",a,b,c,d,this)
})
.load("func"); //在这里的参数就是要创建的重载函数的方法名称。
s.func("a","b");

« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3