JavaScript获取function所有参数名的方法

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

JavaScript获取function所有参数名的方法

铁锚   2020-05-14 我要评论

我写了一个 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所有参数名的方法,本文写的不好还请大家见谅,欢迎大家提出宝贵意见。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们