JS箭头函数

2019-02-21  本文已影响0人  NSWhoohoo

箭头函数的作用域是和定义这个箭头函数的父级上下文绑定在一起的
匿名函数的作用域是和定义匿名函数的上下文绑定在一起的

luke = {
    id: 2,
    say: function() {
        setTimeout(function() {
            console.log(this.id)
        }, 50)
    },
    sayWithThat: function() {
        let that = this
        setTimeout(function() {
            console.log(that.id)
        }, 50)
    },
    sayWithArrow: function() {
        setTimeout(() => {
            console.log(this.id)
        }, 50)
    },
    sayWithGlobalArrow: () => {
        setTimeout(() => {
            console.log(this.id)
        }, 50);
    }
}

luke.say()
luke.sayWithThat()
luke.sayWithArrow()
luke.sayWithGlobalArrow()

有了箭头函数,再也不用写that这种hack

上一篇 下一篇

猜你喜欢

热点阅读