[英]Access Typescript class method or attribute from inner function of another method
Basically the title already explains the problem. 基本上标题已经说明了问题。 I have attached a code extract, which should put my idea across.
我已经附上了代码摘录,应该可以把我的想法付诸实践。
export class MyComponent {
constructor(private element: ElementRef, private myservice:MyService){}
onChange(event: any): void {
// works fine
var imageElem = this.element.nativeElement.querySelector('.image');
reader.onloadend = function() {
// works fine
console.log(imageElem)
// does not work
this.doSome(src);
// does not work
this.myservice.doSome();
}
reader.readAsDataURL(file);
}
doSome(src:string) {}
}
I would leverage arrow function for the onloadend
like: 我会为
onloadend
利用箭头功能 ,例如:
reader.onloadend = () => {
...
}
This way this
will be instance of MyComponent
inside callback because: 这样,
this
将是回调中MyComponent
实例,因为:
arrow functions capture the this value of the enclosing context
箭头函数捕获封闭上下文的this值
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.