JavaScript绑定this

问题描述

var a = {
    one: 1,
    haha() {
        console.log(this.one)
    }
}
setTimeout(a.haha, 1000)

在上例中,函数haha引用了this.one,而定时器结束之后调用的haha传入的this并不是a,输出结果this.one是未定义变量。

方法一:使用箭头函数的方式设置回调

var a = {
    one: 1,
    haha() {
        console.log(this.one)
    }
}
setTimeout(() => {
    a.haha()
}, 1000)

方法二:手动指定this

var a = {
    one: 1,
    haha() {
        console.log(this.one)
    }
}

function go(func) {
    func.bind(a).call()
}

go(a.haha)

猜你喜欢

转载自www.cnblogs.com/weiyinfu/p/10258290.html