改变this指向,JS提供了call()、apply()、bind()三种方法,this指向方法的第一个参数
。
1. call():会调用函数,可以改变this指向
function fn(a, b) {
console.log(this); // {name: 'limi'}
console.log(a + b) // 4
}
fn.call(obj, 1, 3)
call()常用于实现继承
function Animal(name) {
this.name = name;
this.eat = function() {
console.log(this.name + '在吃东西');
}
}
function Dog(name) {
Animal.call(this, name)
}
const dog = new Dog('大白')
dog.eat() // 大白在吃东西
2.apply():会调用函数,可以改变this指向
const arr = ['limi', 24]
function fn2() {
console.log(this); // ['limi', 24]
console.log(this[0]); // limi
}
fn2.apply(arr)
常用于给数组添加方法
const arr1 = [1, 2, 3, 4]
const max = Math.max.apply(Math.max, arr1)
console.log(max); // 4
3.bind():不调用函数,可以改变this指向
const o = { name: '厘米' }
function fn3() {
console.log(this); // { name: '厘米' }
console.log(this['name']); // 厘米
}
const f = fn3.bind(o)
// bind()不调用函数
f()