apply、bind 和 call 这三个方法来改变函数的执行上下文,指定函数中的 this 关键字所指向的对象,并且也可以传递参数。
- call(): 使用 call 方法来调用函数,第一个参数为要绑定到函数的 this 值,后面的参数为传递给函数的参数列表,参数列表以逗号分隔。
function sayHi(greeting) {
console.log(`${greeting}, ${this.name}!`);
}
const person = { name: 'John' };
// 将 sayHi 函数中的 this 绑定到 person 对象上,并传递一个参数
sayHi.call(person, 'Hello');
`- apply():apply 方法与 call 方法相似,不同之处在于它需要传递一个参数数组而不是一系列单独的参数。
function multiply(x, y) {
return x * y;
}
const numbers = [2, 3];
// 将 multiply 函数中的 this 绑定到 window 上,并传递一个参数数组
const result = multiply.apply(null, numbers); // result 的值为 6
- bind():bind 可以创建一个新的函数,并将 this 关键字绑定到指定的对象,并且返回一个新函数,在调用时会自动将绑定的对象作为 this 指向并传递给原函数作为第一个参数,后续调用时只需要提供剩下的参数即可。
const person = { name: 'John' };
function sayHi(greeting) {
console.log(`${greeting}, ${this.name}!`);
}
// 创建一个新函数,将其 this 绑定到 person,返回一个新函数 f
const f = sayHi.bind(person);
// 调用新函数 f,并传递一个参数 greeting
f('Hello'); // 输出 "Hello, John!"