gpt4 book ai didi

javascript - 如何定义将产生调用函数的完整调用的函数

转载 作者:行者123 更新时间:2023-12-03 02:34:35 25 4
gpt4 key购买 nike

我想定义一个可以从其他函数内部调用的日志记录函数。日志记录函数应该打印调用函数的完整调用。例如:

function logger() {}

function F(obj1, obj2) {
logger();
}
F('foo', {bar: 'baz'}); // console output: F('foo', {bar: 'baz'})

我已经通过以下记录器接近了这一点:

function logger(args) {
// Here the arguments objects holds the arguments passed to the
// logger function, not the calling function.
// We use it to get the calling function's name.
let invocation = arguments.callee.caller.toString()
.match(/function ([^\(]+)/)[1];

// invocation === name of calling function

// The arguments object from the calling function is passed
// in as args in order to get the arguments passed with the
// calling function.
let argArray = Array.from(args, function (obj) {
return JSON.stringify(obj);
});

invocation += `(${argArray.join(', ')})`;
console.log(invocation); // Works as intended
}

这可行,但我每次都必须将arguments参数传递给记录器函数:

function F(obj1, obj2) {
logger(arguments);
}

有没有办法避免重复始终向记录器提供arguments参数?

最佳答案

你的答案非常接近:

function logger() {
// Here the arguments objects holds the arguments passed to the
// logger function, not the calling function.
// We use it to get the calling function's name.
let invocation = arguments.callee.caller.toString().match(/function ([^\(]+)/)[1];

// invocation === name of calling function
// The arguments object from the calling function is passed
// in as args in order to get the arguments passed with the
// calling function.
// Here how you can get the caller args - arguments.callee.caller.arguments
let argArray = Array.from(arguments.callee.caller.arguments,
function (obj) {
//Passed function can't be stringified, so by default they
//return empty string and you can just try to get the name or
//make a check if arg is a function object
return JSON.stringify(obj) || obj.name;
});

invocation += `(${argArray.join(', ')})`;
console.log(invocation); // Works as intended
}

function F(obj1, obj2) {
logger(arguments);
}

// console output: F('foo', {bar: 'baz'}, test);
F('foo', {bar: 'baz'}, function test() {});

顺便说一句,请注意,所有这些东西在严格模式下都不起作用,因为那里禁止任何“被调用者”方法。

关于javascript - 如何定义将产生调用函数的完整调用的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48589282/

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