How to call one method in ES6 class from another?

if I have a javascript ES6 class, for example:

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

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

How can I call the writeLine method ??

+5
source share
1 answer

This has nothing to do with es6. In the ajax callback, this no longer refers to an object.

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

Source: https://habr.com/ru/post/1202470/


All Articles