class B{
constructor()
// how to determine the function name in which this object was created?
}
}
function a(){
let b = new B();
}
In the constructor of BI need to find out in which function it was called. I want the function name, which is a
in the given example.
Is this possible with js?
create an Error and use its stack;
function foo() {
var err = new Error();
var stack = err.stack; // This is an array of stack frames
}
Yes, 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();
Yes, with arguments.callee.caller.name
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.