Javascript 如何从另一个方法调用ES6类中的一个方法?

Javascript 如何从另一个方法调用ES6类中的一个方法?,javascript,ecmascript-6,Javascript,Ecmascript 6,如果我有这样一个javascript ES6类: import $ from "jquery"; export class test { constructor() { this.es6 = 'yay'; } writeLine(text){ console.log(text); } getTestData(){ writeLine('writeLine call'); // <-- can not call writeLine ??

如果我有这样一个javascript ES6类:

import $ from "jquery"; 

export class test {

  constructor() {
    this.es6 = 'yay';
  }

  writeLine(text){
    console.log(text);
  }

  getTestData(){
    writeLine('writeLine call'); // <-- can not call writeLine ??
    $.get('/test', function(data){
        console.log(data);
        console.log(data.data);
        this.es6 = data.data;
        debugger
        writeLine(data.data);
    });
 }
} 

如何调用方法
writeLine

这与es6无关。 在ajax回调中,
这个
不再引用对象

getTestData () {

    // this isn't java (see what I did there)
    this.writeLine('writeLine call');

    var _this = this;
    $.get('/test', function (resp) {
        _this.writeLine(resp.data);
    });

    // or
    $.get('/test', function (resp) {
        this.writeLine(resp.data);
    }.bind(this));

    // or
    $.get('/test', resp => this.writeLine(resp.data))
}

您希望第一次调用
this.writeLine
,但在Get中第二次调用不起作用,因为
这个
不是您想象的那样。你要么缓存它,要么绑定它,要么使用fat arrow.or
$.get('/test',data=>this.writeLine(data.data))
@elclanrs我不了解这个巫术。
=>
就像
函数(){}.bind(this)
这不是问题的答案,也没有解决:“writeLine('writeLine call');//我的一个认识是,当使用=>时,您需要在“this”的范围内,这意味着使用构造函数中的=>调用您的方法。这样,它们将保留词法范围到对等方法。您不能将=>扔到已丢失对象“this”的方法中。
getTestData () {

    // this isn't java (see what I did there)
    this.writeLine('writeLine call');

    var _this = this;
    $.get('/test', function (resp) {
        _this.writeLine(resp.data);
    });

    // or
    $.get('/test', function (resp) {
        this.writeLine(resp.data);
    }.bind(this));

    // or
    $.get('/test', resp => this.writeLine(resp.data))
}