The code is still simple. So there's still nothing to explain.
Copy Code code as follows:
/** Koverload
An auxiliary method for creating overloaded functions.
Complements the last function.
@Author Ake 2010-07-03
@weblog HTTP://WWW.CNBLOGS.COM/AKECN
*/
var koverload = function (scope) {
This.scope = Scope | | Window The default Add method to this object. This point of the method that is added at the same time points to the object.
This.list = {}; Where overloaded functions are stored.
return this;
};
Koverload.prototype = {
Add an overloaded method.
@param the method of arg<function> overloading.
Add:function (ARG, types) {
if (typeof arg = = "function") {
var types = (Types | | []). Join (",");
This.list[arg.length + types] = arg; Identifies the storage overload method with the number and type of parameters. Obviously, if your overloaded method parameter number
return this;
}
},
Checktypes:function (Types) {
var type = [];
Console.log (typeof type); [] method creates an array with the TypeOf type Object
If you need to determine the type of words or use Object.prototype.toString.call (type) = = "[Object Array]" to judge it.
For (var i=0, it; it = types[i++];) {
Type.push (typeof it);
}
Return Type.join (",");
},
Call this method to create an overloaded function after you have added all the overloaded functions.
@param fc<string> The method name of the overloaded function.
Load:function (FC) {
var self = This, args, Len, types;
THIS.SCOPE[FC] = function () {///sets the specified method of the specified scope to an overloaded function.
args = Array.prototype.slice.call (arguments); Converts a parameter to an array.
len = args.length;
types = Self.checktypes (args);
Console.log (self.list);
if (Self.list[len + types]) {//To invoke an overloaded method that conforms to the number of arguments.
Self.list[len + types].apply (self.scope, args); Scopes 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:
Copy Code code as follows:
var s = {};
New Koverload (s)//Set the location of the method bindings. Name space?
. 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 argument here is the name of the method of the overloaded function to be created.
S.func ("A", "B");