How to get function parameter names/values dynamically?

前端 未结 30 2592
说谎
说谎 2020-11-22 00:13

Is there a way to get the function parameter names of a function dynamically?

Let’s say my function looks like this:

function doSomething(param1, par         


        
30条回答
  •  抹茶落季
    2020-11-22 00:44

    I know this is an old question, but beginners have been copypasting this around as if this was good practice in any code. Most of the time, having to parse a function's string representation to use its parameter names just hides a flaw in the code's logic.

    Parameters of a function are actually stored in an array-like object called arguments, where the first argument is arguments[0], the second is arguments[1] and so on. Writing parameter names in the parentheses can be seen as a shorthand syntax. This:

    function doSomething(foo, bar) {
        console.log("does something");
    }
    

    ...is the same as:

    function doSomething() {
        var foo = arguments[0];
        var bar = arguments[1];
    
        console.log("does something");
    }
    

    The variables themselves are stored in the function's scope, not as properties in an object. There is no way to retrieve the parameter name through code as it is merely a symbol representing the variable in human-language.

    I always considered the string representation of a function as a tool for debugging purposes, especially because of this arguments array-like object. You are not required to give names to the arguments in the first place. If you try parsing a stringified function, it doesn't actually tell you about extra unnamed parameters it might take.

    Here's an even worse and more common situation. If a function has more than 3 or 4 arguments, it might be logical to pass it an object instead, which is easier to work with.

    function saySomething(obj) {
      if(obj.message) console.log((obj.sender || "Anon") + ": " + obj.message);
    }
    
    saySomething({sender: "user123", message: "Hello world"});
    

    In this case, the function itself will be able to read through the object it receives and look for its properties and get both their names and values, but trying to parse the string representation of the function would only give you "obj" for parameters, which isn't useful at all.

提交回复
热议问题