ES6 的 class 属于一种“语法糖”

Es5:

function Test(x, y) {
    this.x = x;
    this.y = y;
}

Test.prototype.toString = function () {
    return '(' + this.x + ',' + this.y + ')';
}

Es6:

class Test {
    constructor(x, y) {
        this.x = x;
        this.y = y;
    }

    toString() {
        return '(' + this.x + ',' + this.y + ')';
    }
}

其中 constructor 方法是类的构造函数,是一个默认方法,通过 new 命令创建对象实例时,自动调用该方法。一个类必须有 constructor 方法,如果没有显式定义,一个默认的 consructor 方法会被默认添加。所以即使你没有添加构造函数,也是会有一个默认的构造函数的。一般 constructor 方法返回实例对象 this ,但是也可以指定 constructor 方法返回一个全新的对象,让返回的实例对象不是该类的实例。

super()当做函数使用时

class A {
}

class B extends A {
    constructor() {
        super();
    }
}

在 constructor 中必须调用 super 方法,因为子类没有自己的 this 对象,而是继承父类的 this 对象,然后对其进行加工,而 super 就代表了父类的构造函数。
super()也可以当做对象使用,返回的是父类的constructor

总结来说Super()的作用相当于a.prototype.constructor.call(this, props)
此时super内部的this指向b的constructor

class a {
    constructor(a1) {
        this.name = a1;
    }
}

class b extends a {
    constructor(){
        //super('123')
        a.prototype.constructor.call(this, '123')//ES6 要求,子类的构造函数必须执行一次 super 函数,否则会报错。 console.log(this) } } const test = new b()

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注