gpt4 book ai didi

javascript - 如何在 Node Js中获取调用者姓名

转载 作者:行者123 更新时间:2023-12-05 08:11:17 26 4
gpt4 key购买 nike

我正在使用 arguments.callee.caller.name 来获取调用此函数的函数的名称。

例如:

class B {
a = 0;
called_from = false;
setA = (asume)=>{
this.a = assume;
this.called_from = arguments.callee.caller.name;
console.log(this.called_from);
};

callA = ()=>{
this.setA();
};
}

现在我想在日志中获取 callA 名称。

最佳答案

使用来自 Accessing line number in V8 JavaScript (Chrome & Node.js) 的信息

您可以添加一些原型(prototype)以提供从 V8 访问此信息的权限;

Object.defineProperty(global, '__stack', {
get: function() {
var orig = Error.prepareStackTrace;
Error.prepareStackTrace = function(_, stack) {
return stack;
};
var err = new Error;
Error.captureStackTrace(err, arguments.callee);
var stack = err.stack;
Error.prepareStackTrace = orig;
return stack;
}
});

Object.defineProperty(global, '__line', {
get: function() {
return __stack[1].getLineNumber();
}
});

Object.defineProperty(global, '__function', {
get: function() {
return __stack[1].getFunctionName();
}
});

function foo() {
console.log(__line);
console.log(__function);
}

foo()

关于javascript - 如何在 Node Js中获取调用者姓名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61199032/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com