JavaScript call、apply 与 bind用于显式指定普通函数的接收者及部分参数,其中 call 和 apply 立即调用,bind 返回一个新函数。
调用与绑定
call(receiver, ...args) 按参数列表调用;apply(receiver, args) 接受参数数组或类数组;bind(receiver, ...args) 返回绑定接收者和前置参数后的函数,供后续调用。
"use strict";
const user = {
name: "Lin",
read() { return this.name; },
};
const read = user.read;
console.log(read.call({ name: "Chen" })); // Chen
console.log(read.bind(user)()); // Lin
// read() 会因 this 为 undefined 而抛出 TypeError
示例在严格模式下运行。方法被取出后,调用位置不再自带原对象接收者,可以通过显式调用或绑定选择所需接收者。
限制
这些方法不会为箭头函数建立新的 this。绑定函数被用于 new 构造时,绑定的 this 会被忽略,因此“bind 后任何调用都使用同一 this”并不成立。