首页 > Web开发 > 详细

js 获取函数的所有参数名

时间:2017-12-15 20:45:03      阅读:224      评论:0      收藏:0      [点我收藏+]

具体思路:

  利用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;
}

 

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

js 获取函数的所有参数名

原文:http://www.cnblogs.com/shenshangzz/p/8044665.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!