Friday, May 10, 2024
141
rated 0 times [  147] [ 6]  / answers: 1 / hits: 8439  / 10 Years ago, sat, september 13, 2014, 12:00:00

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


More From » ecmascript-6

 Answers
4

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

[#42531] Thursday, September 11, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
milo

Total Points: 62
Total Questions: 99
Total Answers: 97

Location: Sweden
Member since Mon, May 8, 2023
1 Year ago
;