JavaScript获取function所有参数名的方法
笔者编写了一段JavaScript代码,旨在解析并获取函数定义中的所有参数名称,具体实现如下:
function getArgs(func) {
// 先用正则匹配,取得符合参数模式的字符串.
// 第一个分组是这个: ([^)]*) 非右括号的任意字符
var args = func.toString().match(/function\s.*?\(([^)]*)\)/)[1];
// 用逗号来分隔参数(arguments string).
return args.split(",").map(function(arg) {
// 去除注释(inline comments)以及空格
return arg.replace(/\/\*.*\*\//, "").trim();
}).filter(function(arg) {
// 确保没有 undefined.
return arg;
});
}
上述为用于检测参数名的核心函数,以下提供具体的使用示例代码:
function myCustomFn(arg1, arg2,arg3) {
// ...
}
// ["arg1", "arg2", "arg3"]
console.log(getArgs(myCustomFn));
正则表达式(regular expression)在处理特定文本模式时非常强大,虽然其应用场景各异,但在合适的场合下能发挥显著作用。
此外,补充一种在Java语言中获取当前执行函数名的方法:Java 在函数中获取当前函数的函数名
public class Test {
private String getMethodName() {
StackTraceElement[] stacktrace = Thread.currentThread().getStackTrace();
StackTraceElement e = stacktrace[2];
String methodName = e.getMethodName();
return methodName;
}
public void getXXX() {
String methodName = getMethodName();
System.out.println(methodName);
}
public void getYYY() {
String methodName = getMethodName();
System.out.println(methodName);
}
public static void main(String[] args) {
Test test = new Test();
test.getXXX();
test.getYYY();
}
}
【运行结果】
getXXX getYYY
【注意】
需注意代码第5行中堆栈跟踪的索引含义:stacktrace[0].getMethodName() 返回的是 getStackTrace,stacktrace[1].getMethodName() 返回的是 getMethodName 本身,而 stacktrace[2].getMethodName() 才是实际调用 getMethodName 的那个外部函数的名称。
// 注意: stacktrace里面的位置; // [1] 是“getMethodName”, [2] 是调用此方法的method
public static String getMethodName() {
StackTraceElement[] stacktrace = Thread.currentThread().getStackTrace();
StackTraceElement e = stacktrace[2];
String methodName = e.getMethodName();
return methodName;
}
以上内容介绍了如何在JS中获取function的所有参数名,若文中存在不足之处,敬请谅解,欢迎提出宝贵意见。