Why isn't this allowed before super()

前端 未结 3 1002
春和景丽
春和景丽 2020-12-31 09:34

I have been coding in React js. I have read that in ES6 classes to access \'this\' we need to first call super(props) and I would like to know why this is.Answers I have fou

3条回答
  •  孤城傲影
    2020-12-31 09:49

    Constructor function will return 'this' by default. According to oops concept child class always inherit 'this' object from parent class by super() call. so if we try to use this in child class without super call it will throw an error. If we return anything except 'this' from child class then super() call is not necessary. I have explained by some simple examples.

    example 1

    class A {
      constructor() {
        this.a = 0;
      }
    }
    
    class B extends A {
        constructor() {
            console.log(this);
        }
    }
    const instanceA = new A();
    console.log(instanceA) // A {a: 0}
    const instanceB = new B();
    console.log(instanceB) // Error: Must call super constructor in derived class before 
    accessing 'this' or returning from derived constructor 
    

    example 2

    class A {
      constructor() {
        this.a = 0;
      }
    }
    
    class B extends A {
        constructor() {
          return {b: 3}
        }
    }
    const instanceA = new A();
    console.log(instanceA) // A {a: 0}
    const instanceB = new B();
    console.log(instanceB) // Object {b: 3}
    

    example 3

    class A {
      constructor() {
        this.a = 0;
      }
    }
    
    class B extends A {
        constructor() {
          super()
        }
    }
    
    const instanceB = new B();
    console.log(instanceB) // B {a: 0}
    

提交回复
热议问题