[英]Access to class scope inside lambda in TypeScript is undefined?
I have the following class in TypeScript that is used as a Pipe by Angular 2 to render markdown. 我在TypeScript中有以下类,Angular 2将该类用作Pipe来呈现降价促销。 It compiles without errors, but hits an exception at runtime on the marked line:
它编译没有错误,但是在运行时在标记的行上遇到了异常:
var Remarkable = require('remarkable');
@Pipe({
name: 'markdown'
})
export class MarkdownPipe implements PipeTransform {
public remarkable;
constructor(private sanitizer: DomSanitizationService) {
this.remarkable = new Remarkable({
typographer: true
});
this.remarkable.use(this.parseVideos);
}
transform(value: string) : SafeHtml {
if (value != null) {
return this.sanitizer.bypassSecurityTrustHtml(this.remarkable.render(value));
}
return null;
}
public parseVideos(md) : void {
md.inline.ruler.push('video', (state) => {
return this.parseMedia(state, '@', 'video'); // this is undefined
});
}
public parseMedia(state, startingMarker, tokenName) : boolean {
// do stuff
}
}
When I this code attempts to execute, I get a runtime error telling me that: 当我尝试执行此代码时,出现运行时错误告诉我:
Where _this
refers to the same line I have commented above. _this
指向我上面评论的同一行。 Why is this? 为什么是这样? My IDE reports that I should have access to the
parseMedia
method inside of my lambda expression. 我的IDE报告我应该可以访问我的lambda表达式内的
parseMedia
方法。
What's the best solution to this? 最好的解决方案是什么?
That's because you pass it here: 那是因为您在这里传递了它:
this.remarkable.use(this.parseVideos);
Then when the method is invoked the this
no longer points to your instance of MarkdownPipe
. 然后,在调用该方法时,
this
不再指向您的MarkdownPipe
实例。
In order to preserve the right scope for this
you can either have another arrow function: 为了保持合适的范围为
this
你可以有另一个箭头功能:
this.remarkable.use(md => this.parseVideos(md));
Or you can use the Function.prototype.bind() : 或者,您可以使用Function.prototype.bind() :
this.remarkable.use(this.parseVideos.bind(this));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.