改变this指向

改变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()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值