Get function's default value?

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

    I'd tackle it by extracting the parameters from a string version of the function:

    // 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'"}
    

    argument extraction method was taken from here: Regular Expression to get parameter list from function definition

    cheers!

    PS. as you can see, it casts integers into strings, which can be annoying at times. just make sure you know the input type beforehand or make sure it won't matter.

提交回复
热议问题