繁体   English   中英

是否可以在 javascript 中获得父 function 名称?

[英]Is it possible to get parent function name in javascript?

class B{

  constructor()
    // how to determine the function name in which this object was created?
  }

}


function a(){
  let b = new B();

}

在 BI 的构造函数中需要找出在哪个 function 中调用了它。 我想要 function 名称,这是a定示例中的 a 。

这可以用js吗?

创建一个错误并使用它的堆栈;

function foo() {
  var err = new Error();
  var stack = err.stack; // This is an array of stack frames
}

是的,Error.stack...

 class B { constructor() { // how to determine the function name in which this object was created? const ex = new Error() console.log('call from [', ex.stack.split('\n')[2].trim().split(' ')[1], ']'); } } function a() { let b = new B(); } function helloWorld() { let b = new B(); } a(); helloWorld();

是的,使用arguments.callee.caller.name

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM