Get function's default value?

后端 未结 4 432
南笙
南笙 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:44

    As the question states, using toString is a limited solution. It will yield a result that could be anything from a value literal to a method call. However, that is the case with the language itself - it allows such declarations. Converting anything that's not a literal value to a value is a heuristic guess at best. Consider the following 2 code fragments:

    let def;
    function withDef(v = def) {
      console.log(v);
    }
    
    getDefaultValues(withDef); // undefined, or unknown?
    
    def = prompt('Default value');
    withDef();
    
    function wrap() {
      return (new Function(prompt('Function body')))();
      // mutate some other value(s) --> side effects
    }
    
    function withDef(v = wrap()) {
      console.log(v);
    }
    withDef();
    getDefaultValues(withDef); // unknown?
    

    While the first example could be evaluated (recursively if necessary) to extract undefined and later to any other value, the second is truly undefined as the default value is non-determinitic. Of course you could replace prompt() with any other external input / random generator.

    So the best answer is the one you already have. Use toString and, if you want, eval() what you extract - but it will have side effects.

提交回复
热议问题