ES6箭头函数与this、简单分析this指向问题及解决方式

ES6箭头函数与this

  • 首先看普通函数
const person = {
    name: 'tom',
    sayHi: function () {
        console.log(`hi, my name is ${this.name}`);
    }
}
person.sayHi();
  • 输出结果:
hi, my name is tom

普通函数中,this指向调用者,this即person对象

  • 使用箭头函数
const person = {
    name: 'tom',
    sayHi: () => {
        // 这里的this指向箭头函数外、person内的this,即window,window.name=undefined
        console.log(`hi, my name is ${this.name}`);
    }
}
person.sayHi();
  • 输出结果:
hi, my name is undefined

说明箭头函数中的this没有找到name属性
箭头函数在哪定义的,函数中的this就指向所在作用域中的this,即箭头函数外的this

  • 异步执行函数时的this
const person = {
    name: 'tom',
    sayHiAsync: function () {
        setTimeout(function () {
            console.log(`hi, my name is ${this.name}`);
        }, 1000);
    }
}
person.sayHiAsync();
  • 输出结果:
// 延迟1s后控制台打印
hi, my name is undefined

因为setTimeout中的function最终会被放到全局执行上下文中执行,此时的this指向window

  • 解决方法1
    定义一个变量保存当前作用域的this,也是利用了闭包机制
var tmp = 'window';
const person = {
    name: 'tom',
    sayHiAsync: function () {
        const _this = this;
        setTimeout(function () {
            console.log(`hi, my name is ${_this.name}`);
        }, 1000);
    }
}
person.sayHiAsync(); // hi, my name is tom
  • 解决方式2
    使用箭头函数
const person = {
    name: 'tom',
    sayHiAsync: function () {
        setTimeout(() => {
            console.log(`hi, my name is ${this.name}`);
        }, 1000);
    }
}
person.sayHiAsync(); // hi, my name is tom

setTimeout中的function函数体中的this指向的是上层函数体中的this,即sayHiAsync: function() {}中的this,而这里的this取决于谁调用了它,person调用了sayHiAsync,那么相当于person.name


相关资料

理解JS异步编程
javaScript中的this 指向

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值