拆开两层 bind 的调用过程,理解 this 为什么由第一层绑定保留,以及预设参数按什么顺序进入原函数。
JavaScript 连续 bind 两次,为什么 this 没变,参数却多了一个?
时间:2026-12-01
浏览:429
文章目录
给一个已经绑定过的回调再调用一次 bind(),可以预填更多参数。想借这一步顺便换掉 this,就会遇到一个容易忽略的细节。第二次绑定返回了新函数,但普通调用这个新函数时,原函数看到的仍是第一次绑定的对象。
拆开两层调用
第一次 bind() 返回的 withA 保存了对象 first 和参数 'A'。第二次生成的 withAB 以 withA 为调用目标。执行 withAB('C') 时,外层把 second 作为接收者,连同 'B' 和 'C' 一起传入 withA。withA 随即用自己存的 first 调用 describe,并把 'A' 加到参数最前面。
function describe(a, b, c) {
return JSON.stringify([this.label, a, b, c]);
}
const first = { label: 'first' };
const second = { label: 'second' };
const withA = describe.bind(first, 'A');
const withAB = withA.bind(second, 'B');
console.log(withAB('C'));
console.log(withAB.call(second, 'C'));
first。沿着调用顺序读参数就很直观。外层先把 'B' 放在 'C' 前面,内层再把 'A' 放在这两个值前面。describe 最后收到 'A'、'B'、'C'。
第二次打印用的是 withAB.call(second, 'C')。call() 提供的接收者到了 withAB 就被忽略,外层仍使用预先绑定的接收者调用 withA。把 call() 的第一个参数换成另一个对象,打印结果也一样。
要换对象,从原函数创建回调
直接在 describe 上绑定 second,新回调就会以 second 为接收者。把下面两行接在第一段代码后,三个参数依次还是 'A'、'B' 和 'C',输出开头会变成 second。
const withSecond = describe.bind(second, 'A', 'B');
console.log(withSecond('C'));
回调被提前绑定后,有时还会交给另一处代码复用。如果两处需要不同的接收者,可以保留原函数引用,让各调用方独立创建回调。读绑定语句时,就能直接确认会用哪个对象、预填哪些参数。
只想多预填一个参数
如果只需要继续预填参数,可以写 withA.bind(undefined, 'B')。内层的 withA 会忽略这次传入的 undefined,仍用 first 调用 describe。
实用工具推荐
绿化、压缩、噪点和虚拟水印,自由调节做旧程度。
选择画质和输出格式,预览压缩前后的大小。