Rea*_*ues -1 javascript scope this typescript angular
我在TypeScript中有以下类,在Angular 2中用作Pipe来渲染降价。它编译没有错误,但是在运行时在标记的行上遇到了异常:
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
}
}
Run Code Online (Sandbox Code Playgroud)
当我尝试执行此代码时,出现运行时错误告诉我:

凡是_this指我在上面评论过的同一行。为什么是这样?我的IDE报告我应该可以访问parseMedialambda表达式中的方法。

最好的解决方案是什么?
那是因为您在这里传递了它:
this.remarkable.use(this.parseVideos);
Run Code Online (Sandbox Code Playgroud)
然后,在调用该方法时,this不再指向您的实例MarkdownPipe。
为了保留正确的范围,this您可以使用另一个箭头功能:
this.remarkable.use(md => this.parseVideos(md));
Run Code Online (Sandbox Code Playgroud)
或者,您可以使用Function.prototype.bind():
this.remarkable.use(this.parseVideos.bind(this));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
707 次 |
| 最近记录: |