最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get function's default value? - Stack Overflow

programmeradmin2浏览0评论

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

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

Is there a way to get the default value of x here? Optimally, something like:

getDefaultValues(foo); // {"x": 5}

Note that toStringing the function would not work as it would break on defaults that are not constant.

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

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

Is there a way to get the default value of x here? Optimally, something like:

getDefaultValues(foo); // {"x": 5}

Note that toStringing the function would not work as it would break on defaults that are not constant.

Share Improve this question edited Oct 4, 2015 at 14:36 Tushar 87.2k21 gold badges163 silver badges181 bronze badges asked Oct 4, 2015 at 14:35 Benjamin GruenbaumBenjamin Gruenbaum 276k89 gold badges518 silver badges514 bronze badges 5
  • Python, Ruby and C# all do this by the way. – Benjamin Gruenbaum Commented Oct 4, 2015 at 14:43
  • 1 check this stackoverflow.com/questions/894860/… – Or Bachar Commented Oct 4, 2015 at 14:54
  • 5 @OrBachar That is the question of set default parameter, here OP want to get default parameter value from outside of the function without calling it. – Tushar Commented Oct 4, 2015 at 14:56
  • 1 what is the use case ? – Mulan Commented Oct 4, 2015 at 18:50
  • 1 What are you trying to do? This reminds me of Building a LINQ-like query API in JavaScript – Bergi Commented Oct 11, 2015 at 12:27
Add a comment  | 

5 Answers 5

Reset to default 6

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

Is there a way to get the default value of x here?

No, there is no built-in reflection function to do such things, and it is completely impossible anyway given how default parameters are designed in JavaScript.

Note that toString()ing the function would not work as it would break on defaults that are not constant.

Indeed. Your only way to find out is to call the function, as the default values can depend on the call. Just think of

function(x, y=x) { … }

and try to get sensible representation for ys default value.

In other languages you are able to access default values either because they are constant (evaluated during the definition) or their reflection allows you to break down expressions and evaluate them in the context they were defined in.

In contrast, JS does evaluate parameter initializer expressions on every call of the function (if required) - have a look at How does this work in default parameters? for details. And these expressions are, as if they were part of the functions body, not accessible programmatically, just as any values they are refering to are hidden in the private closure scope of the function.
If you have a reflection API that allows access to closure values (like the engine's debugging API), then you could also access default values.

It's quite impossible to distinguish function(x, y=x) {…} from function(x) { var y=x; …} by their public properties, or by their behaviour, the only way is .toString(). And you don't want to rely on that usually.

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.

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.

So, I've seen several other solutions to this question and also on these:

  • How to get function parameter names/values dynamically?

  • Inspect the names/values of arguments in the definition/execution of a JavaScript function

And other methods, besides the ones that rely on external dependencies and parsers, when tested with the following functions break, or return a messy result.

Test cases:

// 1
const testFn1 = (
    nonEmpty=' ',
    end=')', 
    y=end, 
    x, 
    z=x, 
    someCalc = 2*2.3-(2/2),
    comment='//', 
    template='`,', 
    {destructuring, test = '2', ...rest}, 
    {defDestruct, defDestruct_a, defDestruct_b} = {defDestruct: '1', defDestruct_a: 2, defDestruct_b: '3'},
    a = {1: '2', 'hi': [3,4,'==)']},
    anArr = [z,y],
    brackets = (1.23+')'),
    math = Math.round(1.34*10),
    h={a:'ok \"', b:{c:'now=2,tricky=2', d:'rlly'}},
    [test2, destructuring2 = 3, two],
    [destructuring3,, 
        notIgnored],
    [destructuring4, ...rest2],
    [defDestruct2, defDestruct2_a] = [4,5],
    {a: destrct5, c: destrct5_a, e : destrct5_b = 5},
    lastArg
) => {}

//2
const testFn2 = (a, 
    b=2, c={a:2, b:'lol'}, dee, e=[2,3,"a"],/*lol joke=2,2*/ foook=e, g=`test, ok`, h={a:'ok \"', b:{c:'lol=2,tricky=2', d:'lol'}}, i=[2,5,['x']], lastArg = "done" //ajaim, noMatch = 2)
) => {}

 
These are probably unusual cases, but I wanted to propose a stand-alone solution, that covers more edge cases and also returns an object with arguments as keys paired with their default values (evaluated not strings).

const delimiters = {
    brackets: {
        open: ["{","[","("],
        close: ["}","]",")"]
    },
    str: ["'",'"',"`"],
    destructuring: {
        obj: ["{","}"],
        arr: ["[","]"]
    },
    cmmt: {
        open: ["/*","//"],
        close: ["*/", null]
    }
}
/**
 * Parses the parameters of a function.toString() and returns them as an object
 * @param {*} fn The function to get the parameters from
 * @param {*} args arguments to pass to the function
 * @returns An object with the parameters and their default values
 * @author [bye-csavier](https://github.com/bye-csavier)
*/
function parseFnParams(fn, ...args){

    if(typeof fn != 'function') return null;

    let [subStr, parsedArgs, openDelimiters, argList] = ['', "", ['('], ''];
    
    fn = fn.toString().split('') // function to "char" array
    let len = fn.length, READ_ARG = true, INSIDE_STR = false, INSIDE_DESTRUCT = {obj: false, arr: false}, INSIDE_CMMT = {block: false, line: false};
    
    const addArg = () =>{
        subStr = subStr.replace(/\s|\./g, '');
        if(subStr.length == 0) return;
        parsedArgs += `${subStr}:${subStr},\n`;
        subStr = '';
    }

    for(let i=fn.indexOf('(')+1, char; i<len && openDelimiters.length > 0; i++){
        
        char = fn[i];
        let idx = -1;

        if(!INSIDE_STR && !INSIDE_CMMT.block && !INSIDE_CMMT.line){

            if(char == "/" && fn[i+1] == "/") INSIDE_CMMT.line = true;
            else if(char == "/" && fn[i+1] == "*") INSIDE_CMMT.block = true;
            else if(READ_ARG && char == delimiters.destructuring.obj[0]){ INSIDE_DESTRUCT.obj = true; openDelimiters.push(char); idx=0; }
            else if(READ_ARG && char == delimiters.destructuring.arr[0]){ INSIDE_DESTRUCT.arr = true; openDelimiters.push(char); idx=0; }
            else if((INSIDE_DESTRUCT.obj && char == delimiters.destructuring.obj[1]) || (INSIDE_DESTRUCT.arr && char == delimiters.destructuring.arr[1])){
                INSIDE_DESTRUCT.obj = false; INSIDE_DESTRUCT.arr = false;
                if(READ_ARG) addArg();
                openDelimiters.pop(); idx=0;
            }
            else if(delimiters.brackets.open.indexOf(char) > -1) 
            {
                openDelimiters.push(char);
                idx = 0;
            }
            else{
                idx = delimiters.brackets.close.indexOf(char);
                if(idx > -1 && delimiters.brackets.open.indexOf(openDelimiters[openDelimiters.length-1]) == idx) openDelimiters.pop();
            }

        }

        if(INSIDE_CMMT.line){ if(char == "\n") INSIDE_CMMT.line = false; }
        else if(INSIDE_CMMT.block){ if(char == "/" && fn[i-1] == "*") INSIDE_CMMT.block = false; }
        else if(READ_ARG && !INSIDE_STR && idx < 0){
            if(char == ',') addArg();
            else if(char == "="){addArg(); READ_ARG = false;}
            else if(INSIDE_DESTRUCT.obj && char == ':') subStr = "";
            else subStr += char;
        }
        else if((openDelimiters.length == 1 || (INSIDE_DESTRUCT.obj || INSIDE_DESTRUCT.arr)) && char == ',') READ_ARG = true;
        else if(delimiters.str.indexOf(char) > -1){
            if(!INSIDE_STR) INSIDE_STR = char;
            else if(INSIDE_STR == char) INSIDE_STR = false;
        }

        argList += char;
    }
    addArg(); // to also push the last arg

    fn = eval(`(${argList}=>{return {${parsedArgs}}}`);
    parsedArgs = fn(...args);

    return parsedArgs;
}

 
The function is nothing fancy or elegant, and neither is it fast. It does around 12 Ops/sec for the 1° test and 60 Ops/sec for the 2° test. But it's more robust and actually returns the function arguments in an organized way. In the current state, it should be used to precompute the default value of the parameters.

 
To summarize, this function should handle:

  • comments
  • non-constant defaults like (x,y=x)=>{}
  • whitespace
  • passing a list of arguments
  • anonymous functions
  • arrow functions

 
The support for destructuring assignment is limited. It supports only simple desturing assignment like [x,,y=2], {x, y=2}, {a: x, b: y=2}, [x, ...rest], and {x, ...rest}. It doesn't support (meaning that it breaks with): further destructuring like {a, b: {c:d}}; binding pattern as the rest property (e.g [a, b, ...{ length }] or [a, b, ...[c, d]]);

And it also assumes parameters to be wrapped inside round brackets, otherwise it will not work.  

 
Thanks to @Bergi for pointing out the issues in my previous solutions. As @Bergi (and others) said, using an already existing JS parser would be a more reliable solution.

Lastly, I don't know anything about parsing, so any improvement is welcomed.

发布评论

评论列表(0)

  1. 暂无评论