Is it possible to reflect the arguments of a Javascript function?

后端 未结 8 1763
孤城傲影
孤城傲影 2020-12-02 23:21

Is it possible to get all of the arguments a Javascript function is written to accept? (I know that all Javascript function arguments are \"optional\")? If

8条回答
  •  無奈伤痛
    2020-12-03 00:06

    it is possible get all the formal parameter name of a javascript:

    var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m;
    var FN_ARG_SPLIT = /,/;
    var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/;
    var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
    
    function formalParameterList(fn) {
       var fnText,argDecl;
       var args=[];
       fnText = fn.toString().replace(STRIP_COMMENTS, '');
       argDecl = fnText.match(FN_ARGS); 
    
       var r = argDecl[1].split(FN_ARG_SPLIT);
       for(var a in r){
          var arg = r[a];
          arg.replace(FN_ARG, function(all, underscore, name){
             args.push(name);
          });
       }
       return args;
     }
    

    this can be tested this way :

     var expect = require('expect.js');
     expect( formalParameterList(function() {} )).to.eql([]);
     expect( formalParameterList(function () {} )).to.eql([]);
     expect( formalParameterList(function /*  */ () {} )).to.eql([]);
     expect( formalParameterList(function (/* */) {} )).to.eql([]);
     expect( formalParameterList(function ( a,   b, c  ,d /* */, e) {} )).to.eql(['a','b','c','d','e']);
    

    Note: This technique is use with the $injector of AngularJs and implemented in the annotate function. (see https://github.com/angular/angular.js/blob/master/src/auto/injector.js and the corresponding unit test in https://github.com/angular/angular.js/blob/master/auto/injectorSpec.js )

提交回复
热议问题