码迷,mamicode.com
首页 > 编程语言 > 详细

JavaScript绑定this

时间:2019-01-12 01:10:58      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:pre   bind   绑定   方式   定义   回调   箭头函数   javascrip   调用   

问题描述

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)

JavaScript绑定this

标签:pre   bind   绑定   方式   定义   回调   箭头函数   javascrip   调用   

原文地址:https://www.cnblogs.com/weiyinfu/p/10258290.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!