【发布时间】:2019-08-22 05:58:42
【问题描述】:
我看到了很多关于这个话题的讨论,也阅读了很多文章,但我仍然对箭头函数中this 所指的内容感到困惑。
我似乎遇到了与以下代码(简化)相关的运行时错误:
export class Foo implements OnInit {
myProp: string;
myKeys: Array<any> = [];
mySubKeys: Array<any> = [];
@Input myObj;
. . .
ngOnInit() {
this.myKeys = Object.keys(this.myObj);
this.myKeys.forEach((key) => {
this.myProp = key;
this.mySubKeys = Object.keys(this.myObj[key]);
this.mySubKeys.forEach((subkey) => { . . .
. . .
错误发生在this.myProp = key,调试器抱怨this 未定义。
我的困惑是,对于箭头函数,我理解 this 指的是在调用箭头函数的范围之前的 this。在这种情况下,前面的范围不是class,因此不应该定义this.myProp吗?
我尝试将箭头函数更改为 forEach(function(key) { . . . . . . . . . . . 但得到了不同的错误。
最后,如果箭头函数内的this 没有引用class this 那么我如何引用class this 和关联的class 属性(例如@987654339 @) 在箭头函数里面?
【问题讨论】:
-
您可以添加您收到的错误吗?
标签: javascript angular typescript