如何从函数内部访问函数名称?
// 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;
}
Using Function.caller
是非标准的。Function.caller
and arguments.callee
两者在严格模式下都是被禁止的。
编辑:下面 nus 基于正则表达式的答案实现了相同的目标,但具有更好的性能!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)