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

后端 未结 5 1195
北海茫月
北海茫月 2020-11-30 11:03

I\'m looking to do the equivalent of Python\'s inspect.getargspec() in Javascript.

I do know that you can get the arguments list from a Jav

相关标签:
5条回答
  • 2020-11-30 11:34

    Sightly improved version of Jonathan Fingland's answer:

    // Utility function to extract arg name-value pairs
    function getArgs(args) {
        var argsObj = {};
    
        var argList = /\(([^)]*)/.exec(args.callee)[1];
        var argCnt = 0;
        var tokens;
    
        while (tokens = /\s*([^,]+)/g.exec(argList)) {
            argsObj[tokens[1]] = args[argCnt++];
        }
    
        return argsObj;
    }
    
    // Test subject
    function add(number1, number2) {
        var args = getArgs(arguments);
        alert(args.toSource()); // ({number1:3,number2:4})
    }
    
    // Invoke test subject
    add(3, 4);
    

    Note: This only works on browsers that support arguments.callee.

    (Also posted at How to get function parameter names/values dynamically from javascript)

    0 讨论(0)
  • 2020-11-30 11:36

    While I can't see any good reason for this,

    var reg = /\(([\s\S]*?)\)/;
    var params = reg.exec(func);
    if (params) 
         var param_names = params[1].split(',');
    

    assuming func is the name of your function

    0 讨论(0)
  • 2020-11-30 11:39

    here a small nodejs module for that.

    https://github.com/kilianc/node-introspect

    0 讨论(0)
  • 2020-11-30 11:40

    The following function will return an array of parameter names of any function passed in.

    function getParamNames(func) {
        var funStr = func.toString();
        return funStr.slice(funStr.indexOf('(')+1, funStr.indexOf(')')).match(/([^\s,]+)/g);
    }
    

    Example usage:

    getParamNames(getParamNames) // returns ['func']
    getParamNames(function (a,b,c,d){}) // returns ['a','b','c','d']
    
    0 讨论(0)
  • 2020-11-30 11:59

    Here's a version that uses higher order functions. The only thing I don't like about it is that you have to specify parameters as members of an array. But at least they only have to be specified once.

    <!DOCTYPE html>
    
    <html>
    <head>
    <meta charset="UTF-8">
    <title></title>
    <script type="text/javascript">
    var withNamedParams = function(params, lambda) {
        return function() {
            var named = {};
            var max   = arguments.length;
    
            for (var i=0; i<max; i++) {
                named[params[i]] = arguments[i];
            }
    
            return lambda(named);
        };
    };
    
    var foo = withNamedParams(["a", "b", "c"], function(params) {
        for (var param in params) {
            alert(param + ": " + params[param]);
        }
    });
    
    foo(1, 2, 3);
    </script>
    </head>
    <body>
    
    </body>
    </html>
    
    0 讨论(0)
提交回复
热议问题