js 如何在函数体内部知道 自己在哪个函数内运行呢?
打比方:
function a() { ???// 我想在这里知道我的函数名a和函数function a () {...}}
使用Error的调用栈可以匹配到当期执行的函数:
// ???获取正在执行的函数function getExecFunction() { ???let names = new Error().stack.match(/at (.*?) /g); ???let name = names[1].replace(‘at ‘, ‘‘).trim(); ???return eval(name);}
Use Ex:
function a() { ???console.log(getExecFunction());}function getExecFunction() { ???let names = new Error().stack.match(/at (.*?) /g); ???let name = names[1].replace(‘at ‘, ‘‘).trim(); ???return eval(name);}a(); ???????//[Function: a]
如果是在class内部,可以这么写(代码基于ES6):
class A { ???// 获取正在执行的函数 ???getExecFunction() { ???????let names = new Error().stack.match(/at A\.(.*?) /g); ???????let name = names[1].replace(‘at A.‘, ‘‘).trim(); ???????return eval(`this.${name}`); ???} ???a() { ???????console.log(this.getExecFunction()); ???}}new A().a(); ???// ???[Function: a]
如有错误,请指正,感谢。
node.js ?在函数内获取当前函数
原文地址:http://www.cnblogs.com/shenshangzz/p/8044650.html