JavaScript实现函数重载的辅助工具KOverLoad

作者:函数茶馆

时间:2026-10-25

浏览:601

本文介绍了一个名为KOverLoad的JavaScript辅助类,用于简化函数重载的实现。通过参数数量和类型生成唯一标识,将不同实现存储于列表中。在调用时根据实际参数动态匹配并执行对应函数,同时支持指定作用域,适用于需要多态行为的场景。

文章目录

KOverLoad函数重载工具介绍

代码实现保持简洁,因此无需额外解释。


具体代码展示如下:

 
/** 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");
} 
} 
} 
}; 

KOverLoad使用示例

以下是示例:


代码如下:

 
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");

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章