JS 中的 this 指向问题

本文深入探讨了JavaScript中this的指向问题,包括默认指向、通过call、apply和bind改变指向的情况,以及在箭头函数中的特殊行为。通过示例展示了如何在不同场景下理解和使用this,强调了箭头函数不改变this指向的特性。
摘要由CSDN通过智能技术生成

JS 中的 this 指向问题

JavaScriptthis指向是可以改变的, this 默认指向函数外的对象。

下面info函数中的this 默认指向 zs 对象。

let zs = {
    name: "张三",
    age: 12,
    info: function() {
        console.log(this.name + "今年" + this.age + "岁了!")
    }
}

zs.info()
// 张三今年12岁了!

下面是通过call函数改变了 info 中的 this的指向,由zs对象变为ls对象。

let zs = {
    name: "张三",
    age: 12,
    info: function() {
        console.log(this.name + "今年" + this.age + "岁了!")
    }
}

let ls = {
    name: "李四",
    age: 18
}

zs.info.call(ls)
// 李四今年18岁了!

通过调用 call 函数我们就改变了 info 中的 this 指向,其实可以改变 this 指向的函数不止 call,还有 applybind

// apply
zs.info.apply(ls)
// bind
zs.info.bind(ls)()

Tips:ES6 中的箭头函数是不可以改变 this 指向的,箭头函数的 this 永远指向外部函数的 this

let zs = {
    name: "张三",
    age: 12,
    info: function () {
        return () => {
            console.log(this.name + "今年" + this.age + "岁了!")
        }
    }
}

let ls = {
    name: "李四",
    age: 18
}

//zs.info()返回箭头函数再调用call函数
zs.info().call(ls)
// 张三今年12岁了!

此时箭头函数指向为外部函数 this 指向,我们改变外部函数 this指向后再看下箭头函数的 this 指向。

// 先改变info函数的指向再调用箭头函数
zs.info.call(ls)()
// 李四今年18岁了!

我们发现外部函数调用 call 后箭头函数的 this 指向也变了。
End

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值