When writing JS overload functions, we need to determine different input conditions.
However, we generally determine the number of parameters, but this is often not the case:
Function ABC (A, B, C)
A: String
B: Number
C: Boolean
Or
A: String
B: String
C: Number
In both cases, the number of parameters is 3, but the parameter type is completely different. How can we easily build an overloaded function?
Use my class:
Class Code (very short ):
var Param = { varify: function (oParam, sParamType) { var arrParam = sParamType.split(","); if (arrParam.length == oParam.length) { for (var nIndex = 0; nIndex < oParam.length; nIndex++) { if (typeof oParam[nIndex] != String(arrParam[nIndex]).toLowerCase()) { return false; } } return true; } else { return false; } }};
Application Case code:
function modify(s) { switch (true) { case Param.varify(arguments, "string,string,number"): alert(arguments[0] + " " + arguments[1] + "=" + arguments[2].toString()); break; case Param.varify(arguments, "string,string"): alert("Fist Name:"+arguments[1] + "\nLast Name:" + arguments[0]); break; default: alert("nothing"); }}modify("Michael", "Jackson");modify("Michael", "Jackson",5);modify("Michael", "Jackson","King Of Pop");
Run the sample code to experience the pleasure!