gpt4 book ai didi

Javascript:函数绑定(bind)不适用于调用者

转载 作者:行者123 更新时间:2023-11-29 20:28:25 29 4
gpt4 key购买 nike

我有一个函数 foo调用函数 bar . <强> foo绑定(bind)到元素 test .

被调用时,bar存储其 caller集合 foo 内的函数 ( s ) .当我现在运行函数 foo 时里面s , 奇怪 this现在设置为 Window 。但是我确实绑定(bind)了函数,所以我哪里错了?

var s = new Set();

function bar() {
s.add(bar.caller)
}

var test = document.getElementById('test');
test.foo = (function() {
bar();
console.log(this);
}).bind(test);

test.foo(); // output: test div
s.forEach(fn => fn()); // output: Window object
<div id="test"></div>

最佳答案

绑定(bind)函数基本上调用它绑定(bind)的函数 ¹ 与有界 this,所以你的代码的调用堆栈看起来像

 [Bound] test.foo -> test.foo -> bar

所以从 bar 的 Angular 来看,它是从 test.foo 调用的,而不是从绑定(bind)函数调用的。²


¹ 如 spec 中所述:

A bound function is an exotic object that wraps another function object. A bound function is callable (it has a [[Call]] internal method and may have a [[Construct]] internal method). Calling a bound function generally results in a call of its wrapped function


²天气function.caller返回最上面的调用堆栈条目不是很清楚,因为它没有指定。这是一个假设。

关于Javascript:函数绑定(bind)不适用于调用者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58832332/

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