Get function parameter names for interface purposes

前端 未结 5 1254
灰色年华
灰色年华 2021-01-01 03:36

can anyone help me on how to retrieve function parameter names? For example:

var A = function(a, b, c) {};

I need to get the parameter name

5条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-01 04:09

    You can use either a regex such as described in here, another alternative would be to use a tokenizer. The following code uses the acorn javascript parser for checking if a function contains a specific argument name:

    function isFunction(value) {
      return value && typeof value === 'function';
    }
    
    function hasArgument(func, name) {
    
    if (!isFunction(func) || !name) {
        return false;
    }
    
    var tokenizer = acorn.tokenize(func);
    var token = tokenizer();
    
    while (token.type.type !== 'eof') {
    
        // ')' closes function, we do not want to look inside the function body
        if (token.type.type === ')') {
            return false;
        }
    
        if (token.type.type === 'name' && token.value === name) {
            return true;
        }
    
        token = tokenizer();
    
    }
    
    return false;
    

    }

提交回复
热议问题