Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call one method in an ES6 class from another one?

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??

like image 416
tire0011 Avatar asked Sep 13 '14 07:09

tire0011


People also ask

How do you call a method in another class?

Instance methods are built functions into the class definition of an object and require an instance of that class to be called. To call the method, you need to qualify function with self. . For example, in a class that contains functions first() and second(), first() can call second().

How do you call one method from another in JavaScript?

The call() method is a predefined JavaScript method. It can be used to invoke (call) a method with an owner object as an argument (parameter). With call() , an object can use a method belonging to another object.

How do you expose the methods or properties from one class to another?

If it's a static method (doesn't use any instance data), then declare it as a static method and you can directly call it. If it's an instance method, then you would typically create an object of type one and then call the method on that object (usually in the constructor).

How do you call a method inside a class in JavaScript?

var test = new MyObject(); and then do this: test. myMethod();


1 Answers

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))
}
like image 193
Ilia Choly Avatar answered Oct 14 '22 05:10

Ilia Choly