How to get function parameter names/values dynamically?

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

    //See this:
    
    
    // global var, naming bB
    var bB = 5;
    
    //  Dependency Injection cokntroller
    var a = function(str, fn) {
      //stringify function body
      var fnStr = fn.toString();
    
      // Key: get form args to string
      var args = fnStr.match(/function\s*\((.*?)\)/);
      // 
      console.log(args);
      // if the form arg is 'bB', then exec it, otherwise, do nothing
      for (var i = 0; i < args.length; i++) {
        if(args[i] == 'bB') {
          fn(bB);
        }
      }
    }
    // will do nothing
    a('sdfdfdfs,', function(some){
    alert(some)
    });
    // will alert 5
    
    a('sdfdsdsfdfsdfdsf,', function(bB){
    alert(bB)
    });
    
    // see, this shows you how to get function args in string
    

提交回复
热议问题