具体思路:

  利用Function.toString()方法,获取到函数的源码,再利用正则匹配获取到参数名字。

 

实现代码(代码基于ES6):

// 获取函数的参数名
function getParameterName(fn) {
    if(typeof fn !== 'object' && typeof fn !== 'function' ) return;
    const COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
    const DEFAULT_PARAMS = /=[^,)]+/mg;
    const FAT_ARROWS = /=>.*$/mg;
    let code = fn.prototype ? fn.prototype.constructor.toString() : fn.toString();
    code = code
        .replace(COMMENTS, '')
        .replace(FAT_ARROWS, '')
        .replace(DEFAULT_PARAMS, '');
    let result = code.slice(code.indexOf('(') + 1, code.indexOf(')')).match(/([^\s,]+)/g);
    return result === null ? [] :result;
}

 

如有错误,请指正,感谢。

相关文章:

  • 2021-09-08
  • 2022-02-23
  • 2022-12-23
  • 2021-12-06
  • 2022-12-23
  • 2022-02-07
  • 2022-12-23
  • 2021-07-13
猜你喜欢
  • 2021-08-01
  • 2022-12-23
  • 2021-09-08
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案