I am trying to understand the scope of arrow functions. I implemented a small program in Angular, but I got confused a bit. In the code below I don't really understand why this binds to the TestComponent
export class TestComponent {
a: string = "Hello World";
myArrowFunction = () => {
console.log(this.a); //
}
constructor(){
myArrowFunction(); //output: "Hello World"
}
}
Arrow functions don't have its own this
, so the this
binds to the parent, is that right? myArrowFunction
belongs to TestComponent
, so this
in myArrowFunction
should be undefined, but in the example above this
binds to TestComponent
why?
test = {
b: "Hello World",
foo: () => {
console.log(this.b);
}
}
test.foo(); //output: undefined
Where is the difference to the javascript code above? There this.b is undefined.