After going through various discussions and articles on this topic, I find myself still perplexed about the meaning of this
in arrow functions.
I've been encountering run-time errors with a code snippet similar to the following:
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 issue arises at this.myProp = key
where the debugger indicates that this
is undefined.
I'm under the impression that in arrow functions, this
refers to the this
preceding the scope within which the arrow function is called. In this scenario, shouldn't the preceding scope be the class
, making this.myProp
valid?
Attempting to change the arrow function to forEach(function(key) { . . . resulted in different errors.
So if the this
inside the arrow function doesn't point to the class
this
, how can I access the class
this
along with its properties (like myProp
) from within the arrow function?