码迷,mamicode.com
首页 > Web开发 > 详细

js 获取函数的所有参数名

时间:2017-12-15 20:52:05      阅读:250      评论:0      收藏:0      [点我收藏+]

标签:cti   struct   body   replace   row   ret   parameter   indexof   return   

具体思路:

  利用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 获取函数的所有参数名

标签:cti   struct   body   replace   row   ret   parameter   indexof   return   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!