OOP javascript,来自一个方法中的AJAX'语句',如何调用该类的另一个方法?

use*_*454 2 javascript oop ajax jquery

我有这个简单的课程:

class myCustomClass{

    foo(value){
        //do some stuff
    }

    faa(){
        //do some stuff
        $.getJSON( someUrl, function(data) {
            // how call the method foo(value) here ?
            this.foo('fii'); // error occured here, because 'this' is not in 'class' context        
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

当我使用AJAX语句时,如何在方法faa中使用方法'foo(value)'?我不能在这里使用简单的'this.foo(value)',因为AJAX语句中'this'的上下文不是'class'上下文(而是AJAX上下文)

Ror*_*san 5

您需要"缓存"外部作用域中对类的引用,以便可以在AJAX回调的内部作用域中使用,如下所示:

faa() {
  var _class = this; // cache class reference here

  // do some stuff

  $.getJSON(someUrl, function(data) {
    _class.foo('fii'); // use it here
  });
}
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用箭头函数,假设您永远不需要使用回调的内部范围:

faa() {
  // do some stuff

  $.getJSON(someUrl, (data) => {
    this.foo('fii'); // use it here
  });
}
Run Code Online (Sandbox Code Playgroud)