admin管理员组文章数量:1302902
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
??
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
??
-
You want
this.writeLine
– elclanrs Commented Sep 13, 2014 at 7:27 - for the first call it works but not for the second in the get – tire0011 Commented Sep 13, 2014 at 7:40
-
1
Of course, because
this
is not what you think it is. You have to either cache it, bind it, or use fat arrow. – elclanrs Commented Sep 13, 2014 at 7:42
1 Answer
Reset to default 7This 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))
}
本文标签: javascriptHow to call one method in an ES6 class from another oneStack Overflow
版权声明:本文标题:javascript - How to call one method in an ES6 class from another one? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741741309a2395294.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论