8. call()、apply()、bind() 的区别
约 351 字大约 1 分钟
2025-03-12
一、call
call 显式地指定函数中的 this 值,并立即执行该函数。 call 方法接受一个参数列表:第一个参数为指定给 this 的对象,其余的参数为传递给原函数的实参列表
1、语法
call(thisArg);
call(thisArg, arg1);
call(thisArg, arg1, arg2);
call(thisArg, arg1, arg2, /* …, */ argN);
2、示例
function sayHi(age, sex) {
console.log(`Hi, I'm ${this.name}, ${age} year old, a ${sex}`);
}
const person = {
name: "John",
};
sayHi.call(person, "18", "man"); // 输出:Hi, I'm John, 18 year old, a man
sayHi.apply(person); // 输出:Hi, John
2、apply
apply 显式地指定函数中的 this 值,并立即执行该函数。 apply 方法接受两个参数:第一个参数为指定给 this 的对象,第二个参数为一个数组,数组内的参数对应原函数的实参
1、语法
apply(thisArg);
apply(thisArg, argsArray);
2、示例
function sayHi(age, sex) {
console.log(`Hi, I'm ${this.name}, ${age} year old, a ${sex}`);
}
const person = {
name: "John",
};
sayHi.apply(person, ["18", "man"]); // 输出:Hi, I'm John, 18 year old, a man
3、bind
会返回一个改变内部值域的函数,需要再次传入实参来调用来执行
1、语法
bind(thisArg);
bind(thisArg, arg1);
bind(thisArg, arg1, arg2);
bind(thisArg, arg1, arg2, /* …, */ argN);
2、示例
function sayHi(age, sex) {
console.log(`Hi, I'm ${this.name}, ${age} year old, a ${sex}`);
}
const person = {
name: "John",
};
let newSayHi = sayHi.bind(person); // fn(): {}
newSayHi("18", "man"); // 输出:Hi, I'm John, 18 year old, a man
更新日志
2025/8/24 08:17
查看所有更新日志
e7112
-1于