Class A{
A1(){
console.log(`${caller} call A1()`);
}
}
function B1(){
var a=new A();
A1();
}
請問要怎麼樣可以秀出"B1 call A1()"
在非class 的function中可以直接用function.caller 就能得到B1,但定義在class裡的function 好像就沒辦法這麼用了
雖然不曉得為什麼要這麼做,不過可以這樣做
class A {
A1(){
const obj = {};
Error.captureStackTrace(obj, this.A1);
const [stack] = obj.stack.split("\n").slice(1)
const caller = stack.replace(/\s+at ([a-z_0-9]+) \(.*/gim, '$1');
console.log(`${caller} call A1()`); // B1 call A1()
}
}
function B1(){
var a = new A();
a.A1();
}