Sometimes in the encapsulation of a control in many Js functions need to get incoming direct parameters or object parameters, then we need to judge each time the first object, so to facilitate this encapsulation of a function, to get the current function of the parameter values:
/*------------------------------------------* Clears the string of spaces at both ends, including line breaks, tab characters *------------------------------------------* * String.prototype.Trim = function () {return this.replace/(^[\s\n\t]+|[
\s\n\t]+$)/g, ""); /*----------------------------------------* Get the Parameter object of the current function *----------------------------------------* diffcase is case sensitive, default false *----------------------------------------/function Getargs (diffcase) {//Return Parameter object var result = new Ob
Ject ();
Gets the call function var caller = Arguments.callee.caller;
if (caller = NULL | | caller.arguments.length = = 0) return result;
Gets the parameter collection of the function var matchs = caller.tostring (). Match (/\s*function[\w\s]*\ ([\w\s,]*) \)/);
if (matchs = null) return result;
var Argarray = Matchs[1].split (",");
Gets the Parameter object var params = caller.arguments[0]; var index = typeof (params) = = "Object"?
1:0; if (index = = 1) {for (var P-params) {for (var i = 0; i < argarray.length; i++) {var arg = argarray[i].
Trim ();
if (diffcase) {if (arg = = p) { Result[arg] = params[p];
Break
} else {if (arg.tolocalelowercase () = P.tolocalelowercase ()) {Result[arg] = params[p];
Break or more than one parameter overrides the argument passed in by the first argument for (var i = index; i < argarray.length && I < Caller.arg Uments.length; i++) Result[argarray[i].
Trim ()] = caller.arguments[i];
return result; }
Call Example:
Test functions function
test (name, age) {
//Get Parameter object
var args = Getargs ();
Alert ("Name:" + Args.name + ", Age:" + args.age);
}
Invoke Test
("John");
Test ({name: "Dick", age:30});
Test ({name: "Harry"}, 18);