查找函数参数名称

function argumentNames(fn){
       //查找参数列表
       var found = /^[s(]*function[^(]*(s*([^)]*?)s*)/.exec(fn.toString());
       //分隔参数列表
       return found && found[1] ? found[1].split(/,s*/) : [];
};

alert(argumentNames(function(){}).length === 0);
alert(argumentNames(function(x){})[0] === 'x');

var results = argumentNames(function(a,b,c,d,e){});
alert(results[0] == 'a' &&
       results[1] == 'b' &&
       results[2] == 'c' &&
       results[3] == 'd' &&
       results[4] == 'e');

该函数只有几行代码,却使用了很多javascript的高级特性。首先,该函数反编译了传入的函数,并使用正则表达式,将这些参数从逗号分隔的参数列表中抽取出来。

原文地址:https://www.cnblogs.com/gongshunkai/p/6699567.html