Js Gets Implementation Code for Current Function Parameter Object

  • 2021-06-29 09:42:40
  • OfStack

Sometimes when encapsulating a control, we need to get the direct parameters or object parameters passed in many Js functions, so we need to judge the first object each time, so in order to encapsulate a function here, we can get the parameter values in the current function:


/*------------------------------------------
 *  Clear spaces at both ends of the string, including line breaks, tabs 
 *------------------------------------------*/
String.prototype.Trim = function () { return this.replace(/(^[\s\n\t]+|[\s\n\t]+$)/g, ""); }

/*----------------------------------------
 *  Gets the parameter object of the current function 
 *----------------------------------------
 * diffCase  Case sensitive or not, default  false
 *----------------------------------------*/
function GetArgs(diffCase) {

 // Return Parameter Object 
 var result = new Object();

 // Get Call Function 
 var caller = arguments.callee.caller;
 if (caller == null || caller.arguments.length == 0) return result;

 // Gets the set of parameters for a function 
 var matchs = caller.toString().match(/\s*function[\w\s]*\(([\w\s,]*)\)/);
 if (matchs == null) return result;
 var argArray = matchs[1].split(",");

 // Get 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 will 1 Parameters after override the parameters passed in by the object 
 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 
function Test(name, age) {

 // Get Parameter Object 
 var args = GetArgs();

 alert(" Full name: " + args.name + " , age: " + args.age);

}

// Call Test 
Test(" Zhang 3", 25);
Test({ name: " plum 4", age: 30 });
Test({ name: " king 5" }, 18);


Related articles: