如何从函数内部访问函数名?
// 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;
}
使用函数。调用者是非标准的。函数。调用者和实参。在严格模式下,被调用都是被禁止的。
编辑:nus的基于正则表达式的答案实现了同样的事情,但有更好的性能!
这看起来是我这辈子写过的最愚蠢的东西,但很有趣:D
function getName(d){
const error = new Error();
const firefoxMatch = (error.stack.split('\n')[0 + d].match(/^.*(?=@)/) || [])[0];
const chromeMatch = ((((error.stack.split('at ') || [])[1 + d] || '').match(/(^|\.| <| )(.*[^(<])( \()/) || [])[2] || '').split('.').pop();
const safariMatch = error.stack.split('\n')[0 + d];
// firefoxMatch ? console.log('firefoxMatch', firefoxMatch) : void 0;
// chromeMatch ? console.log('chromeMatch', chromeMatch) : void 0;
// safariMatch ? console.log('safariMatch', safariMatch) : void 0;
return firefoxMatch || chromeMatch || safariMatch;
}
D -堆栈深度。0 -返回此函数名,1 -父函数,等等;
[0 + d] -为了理解,会发生什么;
firefoxMatch -适用于safari,但我真的有一点时间测试,因为mac的主人吸烟后回来了,并把我赶走了:'(
测试:
function limbo(){
for(let i = 0; i < 4; i++){
console.log(getName(i));
}
}
function lust(){
limbo();
}
function gluttony(){
lust();
}
gluttony();
结果:
铬:
Fitefox:
这个解决方案只是为了好玩而创造的!不要在实际项目中使用它。它不依赖于ES规范,只依赖于浏览器实现。在下次chrome/firefox/safari更新后,它可能会被破坏。
超过这个数就没有错误(ha)处理-如果d将大于堆栈长度-你将得到一个错误;
对于其他浏览器的错误消息模式-你会得到一个错误;
它必须适用于ES6类(.split('.').pop()),但你仍然可以得到一个错误;