【问题标题】:How to call one method in an ES6 class from another one?如何从另一个类调用 ES6 类中的一种方法?
【发布时间】:2014-09-13 07:25:49
【问题描述】:

如果我有这样的 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);
    });
 }
} 

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

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

如何调用方法writeLine??

【问题讨论】:

  • 你想要this.writeLine
  • 第一次调用有效,但第二次调用无效
  • 当然,因为this 不是你想的那样。您必须缓存它、绑定它或使用粗箭头。

标签: javascript ecmascript-6


【解决方案1】:

这与 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))
}

【讨论】:

  • $.get('/test', data =&gt; this.writeLine(data.data))
  • @elclanrs 我不了解这个巫术。
  • =&gt; 就像function(){}.bind(this)
  • 这不是问题的答案,也没有解决:“writeLine('writeLine call'); //
  • 我对此的一个认识是,当您使用 => 时,您需要在“this”的范围内,这意味着使用构造函数中的 => 调用您的方法。这样他们就保留了对等方法的词法范围。您不能只将 => 扔到已经丢失对象“this”的方法中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-03
  • 1970-01-01
  • 1970-01-01
  • 2014-02-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多