Javascript: 函数绑定不适用于调用方

Javascript: function binding does not work with caller

我有一个调用函数 bar 的函数 foofoo 绑定到元素 test.

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

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>

绑定函数基本上是用有界 this 调用它绑定的函数,所以你的代码的调用栈看起来像

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

所以从 bar 的角度来看,它是从 test.foo 而不是从绑定函数调用的。²


¹ 如 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 returns 最上面的调用堆栈条目不是很清楚,因为它没有指定。这是一个假设。