通过call、apply、bind改变this的指向
call
-
mdn是这样说的:call() 方法使用一个指定的 this 值和单独给出的一个或多个参数来调用一个函数
-
该方法的语法和作用与 apply() 方法类似,只有一个区别,就是 call() 方法接受的是一个参数列表,而 apply() 方法接受的是一个包含多个参数的数组。
const person ={
name:'frank',
age:20,
saiHi(){
console.log(`my name is ${this.name}.I'm ${this.age}years old`)
}
}
const myFriend = {
name:'jack',
age:22
}
console.log(person.saiHi.call(myFriend)) //改变this指向未myFriend,输出my name is jack.I'm 22years old
apply
-
mdn是这样说的:apply() 方法调用一个具有给定this值的函数,以及以一个数组(或类数组对象)的形式提供的参数。
-
注意:call()方法的作用和 apply() 方法类似,区别就是call()方法接受的是参数列表,而apply()方法接受的是一个参数数组。
-
也就是说call后面是接一个一个或多个参数,而apply后面是接一个数组或者伪数组
var array = ['a', 'b'];
var elements = [0, 1, 2];
array.push.apply(array, elements);
console.info(array); // ["a", "b", 0, 1, 2]
bind
- bind() 方法创建一个新的函数,在 bind() 被调用时,这个新函数的 this 被指定为 bind() 的第一个参数,而其余参数将作为新函数的参数,供调用时使用。
const module = {
x: 42,
getX: function() {
return this.x;
}
};
const unboundGetX = module.getX;
console.log(unboundGetX()); // The function gets invoked at the global scope
// expected output: undefined
const boundGetX = unboundGetX.bind(module);
console.log(boundGetX());
// expected output: 42