如何在AJAX调用的回调中访问正确的`this`?

时间:2016-12-25 10:01:53

标签: javascript ajax

我无法在回调函数中访问this,但我最终使用指向AJAX对象的this而不是this调用onClickEmail函数的对象。我尝试在that变量中获取引用,但这也没有多大帮助。

我在这里做错了什么:

onClickEmail() {
  var that = this;
  var hey = "xyz" 
  $.ajax({
    url: 'http://rest.learncode.academy/api/test123/tweets'
  }).then(function(response) {
    console.log(hey);
    console.log(that);
  });
}

除了解决问题之外,我想知道为什么我可以读取hey变量的值,但that未定义

1 个答案:

答案 0 :(得分:0)

this - 变量引用拥有该函数的对象。 使用绑定或尝试

var that = this;
onClickEmail(){
    $.ajax({
            url: 'http://rest.learncode.academy/api/test123/tweets'
        }).then(function(response) {
            hey = that;
        });
}
相关问题