While creating object of class, it throws an error

前端 未结 1 924
挽巷
挽巷 2021-01-23 02:00
class A{
    constructor(){
        this.name=\"A\";
    }
    M1(){
        return \"M1\";
    }
}

class B extends A{
    constructor(){
        this.id=\"B\";
    }
          


        
相关标签:
1条回答
  • 2021-01-23 02:21

    You must call super's constructor.When you call the base class constructor it creates the this and then you can use this.

    class A{
        constructor(){
            this.name="A";
        }
        M1(){
            return "M1";
        }
    }
    
    class B extends A{
        constructor(){
            super();
            this.id="B";
        }
        M2(){
            return "M2";
        }
    }
    

    UPDATED:

    The reason why you need to call the super-constructor from a derived class constructor is due to where ES6 allocates instances – they are allocated by/in the base class (this is necessary so that constructors can be subclassed that have exotic instances, e.g. Array):

    // Base class
    class A {
        // Allocate instance here (done by JS engine)
        constructor() {}
    }
    // Derived class
    class B extends A {
        constructor() {
            // no `this` available, yet
            super(); // receive instance from A
            // can use `this` now
        }
    }
    // Derived class
    class C extends B {
        constructor() {
            // no `this` available, yet
            super(); // receive instance from B
            // can use `this` now
        }
    }
    

    Thanks to Axel Rauschmayer.
    For more see here https://esdiscuss.org/topic/super-on-class-that-extends

    0 讨论(0)
提交回复
热议问题