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

tir*_*011 5 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 ??
    $.get('/test', function(data){
        console.log(data);
        console.log(data.data);
        this.es6 = data.data;
        debugger
        writeLine(data.data);
    });
 }
} 
Run Code Online (Sandbox Code Playgroud)

从另一个文件中导入类并调用getTestData

System.import('app/classDefinition')
.then(function(classDefinitionModul) {
   var test = new classDefinitionModul.test();
   console.log(test.es6);
   test.getTestData();
})
Run Code Online (Sandbox Code Playgroud)

我该如何调用方法writeLine

Ili*_*oly 7

这与es6没有任何关系.在ajax回调中,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))
}
Run Code Online (Sandbox Code Playgroud)

  • 或者`$ .get('/ test',data => this.writeLine(data.data))` (5认同)
  • `=>`就像`function(){}.bind(this)` (3认同)