JS 中的 this 指向问题

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值