ES6中class方法及super关键字

ES6 class中的一些问题

记录下class中的原型,实例,super之间的关系

//父类
class Dad {
    constructor(x, y) {
        this.x = 5;
        this.y = 1;
        this.state = 789
    }

    static x = 521

    state1 = 666

    say() {
        console.log("父类bark");
    }
    talk = () => {
        console.log("父类talk");
    }

    static speak() {
        console.log("父类speak");
        console.log(this.state);
    }
    speak(){
        console.log("父类不会speak");
    }
}
//子类
class Child extends Dad {
    constructor() {
        super()
        this.x = 987
        this.toString = this.toString.bind(this)
    }

    state = {}

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

    toString1 = () => {
        return '(' + this.x + ', ' + this.y + ')';
    }

    say = () => {
        super.say();
        console.log("子类bark");
        console.log(super.x);
    }

    talk = () => {
        super.talk()
        console.log("子类talk");
    }

    static speak() {
        super.speak()
        console.log("子类speak");
        console.log(super.x);
    }

}

console.log(new Child().x); // 输出987
console.log(new Child().y); // 输出1

new Child().say(); // 输出 父类bark  子类bark undefined
new Child().talk(); // 报错 super.talk is not a function

Child.speak(); // 父类speak undefined 子类speak 521
  1. 构造器中的this指向实例对象,在构造函数上定义的属性和方法相当于定义在类实例上的,而不是原型对象上

  2. 子类的toString方法是挂载到原型上的,toString1是挂载到每个实例上的

  3. this.toString.bind(this),前面的this是不确定的,取决于调用方式;
    后面的this指实例对象,这行代码目的是为了固定toString方法的this为实例对象,避免函数赋值给变量时this丢失

  4. super关键字用于访问和调用一个对象的父对象上的函数

  5. super作为函数使用,调用的是父类的构造函数,而其中的this指向子类自己(用父类的方法操作自己的东西)

  6. super 作为对象时,在普通方法中,指向父类的原型对象(只能访问原型上的函数,无法访问属性);在静态方法中,指向父类本身(调用的是父类的静态方法或属性),但是this指向子类。

posted @ 2022-07-21 15:15  lupulus  阅读(239)  评论(0编辑  收藏  举报