In other words, people are motivated to be concerned. So I modified the "auxiliary method for adding JavaScript overload functions" written last time, and added a parameter to restrict the parameter type when adding the method. The code is still simple. So there is still no explanation ..
The Code is as follows:
/** KOverLoad
An auxiliary method for creating overloaded functions.
Supplement the previous function.
@ Author ake 2010-07-03
@ Weblog http://www.cnblogs.com/akecn
*/
Var KOverLoad = function (scope ){
This. scope = scope | window; // Add the method to this object by default. This of the method added at the same time points to this object.
This. list = {}; // The place where the overload function is stored.
Return this;
};
KOverLoad. prototype = {
// Add an overloaded method.
// @ Param arg Method.
Add: function (arg, types ){
If (typeof arg = "function "){
Var types = (types | []). join (",");
This. list [arg. length + types] = arg; // identifies the storage overload method by the number and type of parameters. Obviously, if you overload the number of method parameters
Return this;
}
},
CheckTypes: function (types ){
Var type = [];
// Console. log (typeof type); an array created in [] mode, whose typeof type is object
// Use Object. prototype. toString. call (type) = "[object Array]" to determine the type.
For (var I = 0, it; it = types [I ++];) {
Type. push (typeof it );
}
Return type. join (",");
},
// Call this method to create an overloaded function after adding all the overloaded functions.
// @ Param fc Method Name of the overload function.
Load: function (fc ){
Var self = this, args, len, types;
This. scope [fc] = function () {// sets the specified method of the specified scope as an overloaded function.
Args = Array. prototype. slice. call (arguments); // convert the parameter to an Array.
Len = args. length;
Types = self. checkTypes (args );
// Console. log (self. list );
If (self. list [len + types]) {// call the conforming overload 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 ");
}
}
}
};
The following is an example:
The Code is as follows:
Var s = {};
New KOverLoad (s) // set the location of the method binding. Namespace?
. Add (function (){
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 method name of the overload function to be created.
S. func ("a", "B ");