Get function's default value?

后端 未结 4 444
南笙
南笙 2021-01-04 02:57

Is there a way to retrieve a function\'s default argument value in JavaScript?

function foo(x = 5) {
    // things I do not control
}

Is th

4条回答
  •  情深已故
    2021-01-04 03:31

    Since we don't have classic reflection in JS, as you can find on C#, Ruby, etc., we have to rely on one of my favorite tools, regular expressions, to do this job for us:

    let b = "foo";
    function fn (x = 10, /* woah */ y = 20, z, a = b) { /* ... */ }
    
    fn.toString()
      .match(/^function\s*[^\(]*\(\s*([^\)]*)\)/m)[1] // Get the parameters declaration between the parenthesis
      .replace(/(\/\*[\s\S]*?\*\/)/mg,'')             // Get rid of comments
      .split(',')
      .reduce(function (parameters, param) {          // Convert it into an object
        param = param.match(/([_$a-zA-Z][^=]*)(?:=([^=]+))?/); // Split parameter name from value
        parameters[param[1].trim()] = eval(param[2]); // Eval each default value, to get strings, variable refs, etc.
    
        return parameters;
      }, {});
    
    // Object { x: 10, y: 20, z: undefined, a: "foo" }
    

    If you're going to use this, just make sure you're caching the regexs for performance.

    Thanks to bubersson for hints on the first two regexs

提交回复
热议问题