How to get function parameter names/values dynamically?

前端 未结 30 2622
说谎
说谎 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:33

    I don't know how to get a list of the parameters but you can do this to get how many it expects.

    alert(doSomething.length);
    
    0 讨论(0)
  • 2020-11-22 00:33

    I have modified the version taken from AngularJS that implements a dependency injection mechanism to work without Angular. I have also updated the STRIP_COMMENTS regex to work with ECMA6, so it supports things like default values in the signature.

    var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m;
    var FN_ARG_SPLIT = /,/;
    var FN_ARG = /^\s*(_?)(.+?)\1\s*$/;
    var STRIP_COMMENTS = /(\/\/.*$)|(\/\*[\s\S]*?\*\/)|(\s*=[^,\)]*(('(?:\\'|[^'\r\n])*')|("(?:\\"|[^"\r\n])*"))|(\s*=[^,\)]*))/mg;
    
    function annotate(fn) {
      var $inject,
        fnText,
        argDecl,
        last;
    
      if (typeof fn == 'function') {
        if (!($inject = fn.$inject)) {
          $inject = [];
          fnText = fn.toString().replace(STRIP_COMMENTS, '');
          argDecl = fnText.match(FN_ARGS);
          argDecl[1].split(FN_ARG_SPLIT).forEach(function(arg) {
            arg.replace(FN_ARG, function(all, underscore, name) {
              $inject.push(name);
            });
          });
          fn.$inject = $inject;
        }
      } else {
        throw Error("not a function")
      }
      return $inject;
    }
    
    console.log("function(a, b)",annotate(function(a, b) {
      console.log(a, b, c, d)
    }))
    console.log("function(a, b = 0, /*c,*/ d)",annotate(function(a, b = 0, /*c,*/ d) {
      console.log(a, b, c, d)
    }))
    annotate({})

    0 讨论(0)
  • 2020-11-22 00:33

    Here's one way:

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

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

    0 讨论(0)
  • 2020-11-22 00:34

    A lot of the answers on here use regexes, this is fine but it doesn't handle new additions to the language too well (like arrow functions and classes). Also of note is that if you use any of these functions on minified code it's going to go

    0 讨论(0)
  • 2020-11-22 00:34

    I'll give you a short example below:

    function test(arg1,arg2){
        var funcStr = test.toString()
        var leftIndex = funcStr.indexOf('(');
        var rightIndex = funcStr.indexOf(')');
        var paramStr = funcStr.substr(leftIndex+1,rightIndex-leftIndex-1);
        var params = paramStr.split(',');
        for(param of params){
            console.log(param);   // arg1,arg2
        }
    }
    
    test();
    
    0 讨论(0)
  • 2020-11-22 00:34

    Ok so an old question with plenty of adequate answers. here is my offering that does not use regex, except for the menial task of stripping whitespace . (I should note that the "strips_comments" function actually spaces them out, rather than physically remove them. that's because i use it elsewhere and for various reasons need the locations of the original non comment tokens to stay intact)

    It's a fairly lengthy block of code as this pasting includes a mini test framework.

        function do_tests(func) {
    
        if (typeof func !== 'function') return true;
        switch (typeof func.tests) {
            case 'undefined' : return true;
            case 'object'    : 
                for (var k in func.tests) {
    
                    var test = func.tests[k];
                    if (typeof test==='function') {
                        var result = test(func);
                        if (result===false) {
                            console.log(test.name,'for',func.name,'failed');
                            return false;
                        }
                    }
    
                }
                return true;
            case 'function'  : 
                return func.tests(func);
        }
        return true;
    } 
    function strip_comments(src) {
    
        var spaces=(s)=>{
            switch (s) {
                case 0 : return '';
                case 1 : return ' ';
                case 2 : return '  ';
            default : 
                return Array(s+1).join(' ');
            }
        };
    
        var c1 = src.indexOf ('/*'),
            c2 = src.indexOf ('//'),
            eol;
    
        var out = "";
    
        var killc2 = () => {
                    out += src.substr(0,c2);
                    eol =  src.indexOf('\n',c2);
                    if (eol>=0) {
                        src = spaces(eol-c2)+'\n'+src.substr(eol+1);
                    } else {
                        src = spaces(src.length-c2);
                        return true;
                    }
    
                 return false;
             };
    
        while ((c1>=0) || (c2>=0)) {
             if (c1>=0) {
                 // c1 is a hit
                 if ( (c1<c2) || (c2<0) )  {
                     // and it beats c2
                     out += src.substr(0,c1);
                     eol = src.indexOf('*/',c1+2);
                     if (eol>=0) {
                          src = spaces((eol-c1)+2)+src.substr(eol+2);
                     } else {
                          src = spaces(src.length-c1);
                          break;
                     }
                 } else {
    
                     if (c2 >=0) {
                         // c2 is a hit and it beats c1
                         if (killc2()) break;
                     }
                 }
             } else {
                 if (c2>=0) {
                    // c2 is a hit, c1 is a miss.
                    if (killc2()) break;  
                 } else {
                     // both c1 & c2 are a miss
                     break;
                 }
             }
    
             c1 = src.indexOf ('/*');
             c2 = src.indexOf ('//');   
            }
    
        return out + src;
    }
    
    function function_args(fn) {
        var src = strip_comments(fn.toString());
        var names=src.split(')')[0].replace(/\s/g,'').split('(')[1].split(',');
        return names;
    }
    
    function_args.tests = [
    
         function test1 () {
    
                function/*al programmers will sometimes*/strip_comments_tester/* because some comments are annoying*/(
                /*see this---(((*/ src//)) it's an annoying comment does not help anyone understand if the 
                ,code,//really does
                /**/sucks ,much /*?*/)/*who would put "comment\" about a function like (this) { comment } here?*/{
    
                }
    
    
            var data = function_args(strip_comments_tester);
    
            return ( (data.length==4) &&
                     (data[0]=='src') &&
                     (data[1]=='code') &&
                     (data[2]=='sucks') &&
                     (data[3]=='much')  );
    
        }
    
    ];
    do_tests(function_args);
    
    0 讨论(0)
提交回复
热议问题