gpt4 book ai didi

javascript - func.apply 且 THIS 不应用于任何对象

转载 作者:行者123 更新时间:2023-11-28 03:40:56 33 4
gpt4 key购买 nike

我不明白为什么以下代码将 thisarguments 传递给 func.apply

我尝试使用代码来弄清楚它在做什么,在互联网上搜索等,但找不到任何关于以这种方式使用 apply 的信息。

 function work(a, b) {
alert( a + b );
}

function spy(func) {
function wrapper(...args) {
wrapper.calls.push(args);
return func.apply(this,arguments);
}
wrapper.calls = []
return wrapper;
}
work = spy(work)
work(1, 2); // 3
work(4, 5); // 9

以下调用返回wrapper的结果

work.apply(this,arguments(a,b))

spy的结果与上面相同。但是是什么让 thisarguments 在包装器中做正确的事情呢?因为如果没有 this 它就不起作用,为什么当我声明

let work = spy(work) 

这不起作用。

最佳答案

work 已在此处声明(函数声明)。如果您想重新声明,可以使用 var 来代替。

在此特定示例中,您没有在 work 函数中使用 this。因此,即使您像下面这样 func(...args) 调用 func 也没有什么区别:

function work(a, b) {
alert( a + b );
}

function spy(func) {
function wrapper(...args) {
wrapper.calls.push(args);
console.log({ this: this });
return func(...args);
}
wrapper.calls = []
return wrapper;
}
var work = spy(work)
work(1, 2);
work(4, 5);

关于javascript - func.apply 且 THIS 不应用于任何对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57312338/

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