I have problem with 'this' keyword in typescript. As you can see below, I want to call method1 from some 'inside' function, for example FileReader.onloadend method. Hovewer, 'this' references to FileReader, not to class foo. How can I change my code to make this work?
export class foo {
constructor() {
this.method2();
}
public method1() {
console.log('method1 called'); // this never happens
}
public method2() {
let reader: FileReader = new FileReader();
reader.onloadend = function(e) {
console.log(this) //it prints FileReader object
this.method1(); //I want this to be refered to class foo
}
}
}
答案 0 :(得分:2)
Use the new function literal syntax with far arrows:
public method2() {
let reader: FileReader = new FileReader();
reader.onloadend = (e) => {
console.log(this) //it no longer prints FileReader object
this.method1(); //method1 called
}
}
Using far arrows, this
now always refers to the class, instead of the function scope. You can check out the MDN for more information on Lexical this
and the short form function syntax.
The documentation is for ES6, but it applies equally to Typescript, since it's a strict superset.
答案 1 :(得分:1)
Change this:
reader.onloadend = function(e) {
console.log(this) //it prints FileReader object
this.method1(); //I want this to be refered to class foo
}
to this:
reader.onloadend = (e) => {
console.log(this) //it prints FileReader object
this.method1(); //I want this to be refered to class foo
}
You can read more about arrow functions here.