Search code examples
javascripttypescriptbindingarrow-functions

Why does Typescript arrow function property has access to this


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.


Solution

  • This is normal, because of the arrow function this refers to the upper object so your instance.

    
    //console.log(this)
    class TestComponent {
        myArrowFunction = () => {// function set in instance
            console.log(this); //
        }
        myFunction() {// function set in prototype
            console.log(this); //
        }
        constructor() {
            this.a = "Hello World";
            this.myArrowFunction(); //output: "Hello World"
        }
    }
    
    function A() {
        this.foo = () => { console.log(this) };// A instance
        this.foo()
    }
    A.prototype.bar = () => { console.log(this) };// global
    new A();
    //const a = new TestComponent();