在创建类的对象时

在创建类的对象时

本文介绍了在创建类的对象时,会抛出错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class A{
    constructor(){
        this.name="A";
    }
    M1(){
        return "M1";
    }
}

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

var b = new B();

输出


推荐答案

你必须调用 super的构造函数。当你调用基类构造函数时,它会创建这个和然后你可以使用这个

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";
    }
}

更新:

你需要从派生类构造函数调用超构造函数的原因是由于ES6分配实例的地方 - 它们是由/在基类中分配的(这是必要的)这样构造函数可以被子类化,具有异常实例,例如Array):

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
    }
}

感谢 Axel Rauschmayer

欲了解更多信息,请点击此处

这篇关于在创建类的对象时,会抛出错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 22:43