I've seen a lot of discussion on this topic, and I've read through numerous articles, but I'm still confused about what this
refers to in arrow functions.
I seem to be getting run-time errors associated with the following code (simplified):
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) => { . . .
. . .
The error happens at this.myProp = key
where the debugger complains that this
is undefined.
My confusion is that for arrow functions I understood that this
refers to the this
preceding the scope in which the arrow function is called. In this case, wouldn't the preceding scope be the class
scope, and therefore shouldn't this.myProp
be defined?
I tried changing the arrow function to forEach(function(key) { . . . but got different errors.
Finally, if the this
inside the arrow function doesn't refer to the class
this
then how do I refer to the class
this
and associated class
properties (such as myProp
) inside the arrow function?