apply
方法其实就是改变某个方法的 this
指向,并且可以向该函数传参(数组形式参数)。
const s1 = {
name: "张三",
age: 22,
};
const s2 = {
name: "李四",
age: 44,
};
const s3 = {
name: "王五",
age: 66,
hello: function (trashTalking = "", ...args) {
console.log(
// 注意 this 指向的对象
// ...args 剩余参数的数组
// ?? 空值合并操作符
this.age + "岁的" + this.name + trashTalking + (args[0] ?? "")
);
},
};
s3.hello(); // 66岁的王五
s3.hello.apply(s1, ["你还好吗"]); // 22岁的张三你还好吗
s3.hello.apply(s2, ["芜湖", 1, "起飞"]); // 44岁的李四芜湖1
s3.hello.apply({ name: "小胡", age: 99 }, ["你是伞兵"]); // 99岁的小胡你是伞兵
可以改变 this
指向的还有 call
和 bind
,call
的区别是可以传多个参数,bind
返回的值是新函数,需要再手动执行一次。
s3.hello.call(s1, "call", 2); // 22岁的张三call2
s3.hello.bind(s2, "bind", 3)(); // 44岁的李四bind3 返回的是新函数,需调用