如何从函数内部访问函数名?
// 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();
这看起来是我这辈子写过的最愚蠢的东西,但很有趣: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()),但你仍然可以得到一个错误;
这可能对你有用:
function foo() { bar(); }
function bar() { console.log(bar.caller.name); }
如果从匿名函数调用,运行foo()将输出“foo”或未定义。
它也适用于构造函数,在这种情况下,它将输出调用构造函数的名称(例如“Foo”)。
更多信息请访问:https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/Caller
他们声称这是不标准的,但所有主流浏览器都支持它:Firefox、Safari、Chrome、Opera和IE。