栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > Web开发 > JavaScript

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

JavaScript 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

var KOverLoad = function(scope) {
this.scope = scope || window; //默认添加方法到这个对象中。同时添加的方法的this指向该对象。
this.list = {}; //存放重载函数的地方。
return this;
};
KOverLoad.prototype = {
//添加一个重载的方法。
//@param arg 重载的方法。
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 重载函数的方法名。
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");
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/115709.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号