Js obtains the implementation code of the current function parameter object.
Sometimes, when encapsulating controls, you need to obtain the input direct parameters or object parameters in many Js functions. Therefore, we need to judge the first object every time, therefore, to encapsulate a function here to obtain the parameter values of the current function:
/* -------------------------------------- * Clear spaces at both ends of the String, including line breaks and tabs * ---------------------------------------- */String. prototype. trim = function () {return this. replace (/(^ [\ s \ n \ t] + | [\ s \ n \ t] + $)/g ,"");} /* optional * Get the parameter object of the current function * -------------------------------------- * case-sensitive diffCase. The default value is false * ---------------------------------- */function GetArgs (diffCase) {// Return the parameter Object var result = new Object (); // obtain the call function var caller = arguments. callee. caller; if (caller = null | caller. arguments. length = 0) return result; // obtain the function's parameter set var matchs = caller. toString (). match (/\ s * function [\ w \ s] * \ ([\ w \ s,] *) \)/); if (matchs = null) return result; var argArray = matchs [1]. split (","); // get the parameter object var params = caller. arguments [0]; var index = typeof (params) = "object "? 1: 0; if (index = 1) {for (var p in 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 ;}}}}} // multiple parameters overwrite the parameters after the first one to the for (var I = index; I <argArray. length & I <caller. arguments. length; I ++) result [argArray [I]. trim ()] = caller. arguments [I]; return result ;}
Call example:
// Test function Test (name, age) {// obtain the parameter object var args = GetArgs (); alert ("name:" + args. name + ", age:" + args. age) ;}// call the Test ("Zhang San", 25); Test ({name: "Li Si", age: 30}); Test ({name: "Wang Wu"}, 18 );