The code is still simple. So there's still nothing to explain. .
/**KOverLoad
A helper method for creating overloaded functions.
Supplement the last function.
@Author ake 2010-07-03
@weblog http://www.cnblogs.com/akecn
*/
var KOverLoad = function(scope) {
this.scope = scope || window; //Add methods to this object by default. The this of the method added at the same time points to the object.
this.list = {}; //A place to store overloaded functions.
return this;
};
KOverLoad.prototype = {
//Add an overloaded method.
//@param arg Overloaded method.
add:function(arg, types) {
if(typeof arg == "function") {
var types = (types || []).join(",");
this.list[arg.length types] = arg; //Storage overloaded methods identified by the number and type of parameters. Obviously if the number of parameters in your overloaded method
return this;
}
},
checkTypes: function(types) {
var type = [];
//console .log(typeof type); The typeof array created by [] method is object
//If you need to determine the type, use Object.prototype.toString.call(type) == "[object Array]" Judge it.
for(var i=0, it; it = types[i ];) {
type.push(typeof it);
}
return type.join(",");
},
//After adding all overloaded functions, call this method to create overloaded functions.
//@param fc The method name of the overloaded function.
load:function(fc) {
var self = this, args, len, types;
this.scope[fc] = function() { //Set the specified method in the specified scope to reset load function.
args = Array.prototype.slice.call(arguments); //Convert parameters to array.
len = args.length;
types = self.checkTypes(args);
//console.log(self.list);
if(self.list[len types]) { / /Call the corresponding overloaded method based on the number of parameters.
self.list[len types].apply(self.scope, args); //The scope and parameters are specified here.
}else if(self.list[len]){
self.list[len].apply(self.scope, args)
}else {
throw new Error("undefined overload type ");
}
}
}
};
Here is an example:
var s = {};
new KOverLoad(s) //Set the location of method binding. Namespace?
.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"); //The parameter here is the reload to be created The method name of the loaded function.
s.func("a","b");