如何从函数内部访问函数名称?
// parasitic inheritance
var ns.parent.child = function() {
var parent = new ns.parent();
parent.newFunc = function() {
}
return parent;
}
var ns.parent = function() {
// at this point, i want to know who the child is that called the parent
// ie
}
var obj = new ns.parent.child();
最佳答案
在 ES6 中,你可以只使用 myFunction.name
。
注意:请注意一些 JS 压缩器可能会丢弃函数名称,以便更好地压缩;你可能需要调整他们的设置来避免这种情况。
在 ES5 中,最好的做法是:
function functionName(fun) {
var ret = fun.toString();
ret = ret.substr('function '.length);
ret = ret.substr(0, ret.indexOf('('));
return ret;
}
使用 Function.caller
是非标准的。 Function.caller
和 arguments.callee
在严格模式下都被禁止。
编辑:下面 nus 的基于正则表达式的答案实现了相同的目标,但性能更好!
关于javascript - 如何从该函数中获取函数名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2648293/