如何从另一个ES6类中调用一个方法? [英] How to call one method in an ES6 class from another one?

查看:2807
本文介绍了如何从另一个ES6类中调用一个方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  import $ fromjquery; 

export class test {

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

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

getTestData(){
writeLine('writeLine call'); //< - 不能调用writeLine?
$ .get('/ test',function(data){
console.log(data);
console.log(data.data);
this.es6 = data.data;
调试器
writeLine(data.data);
});
}
}

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

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

如何调用方法 writeLine ??

解决方案

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

 code getTestData(){

//这不是java(看我在那里做什么)
this.writeLine('writeLine call');

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

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

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


if I have a javascript ES6 class like this:

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);
    });
 }
} 

From another file I import the class and call getTestData

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

How can I call the method writeLine??

解决方案

This doesn't have anything to do with es6. In the ajax callback, this doesn't refer to the object anymore.

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

这篇关于如何从另一个ES6类中调用一个方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆