获取函数的默认值?

Ben*_*aum 15 javascript default-arguments ecmascript-6

有没有办法在JavaScript中检索函数的默认参数值?

function foo(x = 5) {
    // things I do not control
}
Run Code Online (Sandbox Code Playgroud)

有没有办法获得x这里的默认值?最理想的是,像:

getDefaultValues(foo); // {"x": 5}
Run Code Online (Sandbox Code Playgroud)

请注意,toString该函数不起作用,因为它会在非常量的默认值上中断.

pil*_*lau 5

由于我们在JS中没有经典的反映(可以在C#,Ruby等上找到),因此我们必须依靠我最喜欢的工具之一(正则表达式)为我们完成这项工作:

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" }
Run Code Online (Sandbox Code Playgroud)

如果要使用此功能,只需确保要缓存正则表达式以提高性能。

感谢bubersson对前两个正则表达式的提示

  • 如果环境不一样,这会中断:`function foo(){var x = 5; 返回函数bar(y = x){}}; var bar = foo();` (2认同)
  • 不,因为您必须对其进行评估,否则会产生副作用。例如`function foo(){var x =提示(“请输入数字”); 返回函数(y = x){}; } var bar = foo()`-您将如何在此处绑定值“ y”? (2认同)

sil*_*kes 1

我通过从函数的字符串版本中提取参数来解决这个问题:

// making x=3 into {x: 3}
function serialize(args) {
  var obj = {};
  var noWhiteSpace = new RegExp(" ", "g");
  args = args.split(",");
  args.forEach(function(arg) {
    arg = arg.split("=");
    var key = arg[0].replace(noWhiteSpace, "");
    obj[key] = arg[1];
  });
  return obj;
  }

 function foo(x=5, y=7, z='foo') {}

// converting the function into a string
var fn = foo.toString();

// magic regex to extract the arguments 
var args = /\(\s*([^)]+?)\s*\)/.exec(fn);

//getting the object
var argMap = serialize(args[1]); //  {x: "5", y: "7", z: "'foo'"}
Run Code Online (Sandbox Code Playgroud)

参数提取方法取自此处:Regular Expression to getparameterlistfromfunctiondefinition

干杯!

附言。正如您所看到的,它将整数转换为字符串,这有时会很烦人。只需确保您事先知道输入类型或确保它无关紧要。