下面代码中,连续 bind 多次,输出什么?
参考答案
题干未附代码,但结论固定:bind 只有第一次生效。
function f() { return this.name; }
const g = f.bind({ name: 'A' }).bind({ name: 'B' });
g(); // 'A'
原因:bind 返回的是"绑定函数"(Bound Function),其内部 [[BoundThis]] 已固定;再次 bind 时按规范,新的绑定目标是那个绑定函数,但被调用时仍用最初绑定的 this(后续 bind 只影响参数,不影响 this)。
若是 f.bind(a).call(b) 也仍是 a。