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

我写了一个 JavaScript函数来解析函数的参数名称,代码如下:

rush:js;"> 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; }); }

上面是检测的函数,示例代码如下:

rush:js;"> function myCustomFn(arg1,arg2,arg3) { // ... } // ["arg1","arg2","arg3"] console.log(getArgs(myCustomFn));

正则表达式(regular expression) 是个好东西吗? 别的我不知道,但在适当的场景用起来还是很给力的!

附带一个Java取得当前函数名的方法: Java 在函数获取当前函数函数

rush: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

rush:java;"> public static String getmethodName() { StackTraceElement[] stacktrace = Thread.currentThread().getStackTrace(); StackTraceElement e = stacktrace[2]; String methodName = e.getmethodName(); return methodName; }

以上内容是本文给大家介绍的js获取function所有参数名的方法,本文写的不好还请大家见谅,欢迎大家提出宝贵意见。

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...