class类的基本用法 及 继承

2022-06-24  本文已影响0人  青城墨阕

基本用法

class Person {
    // 类的静态属性,关键字static,给类自身添加属性
    static staticFun = function() {
        console.log('类的静态属性,关键字static,给类自身添加属性');
    };

    // constructor 类的构造方法,会自执行
    constructor(name, age) {
        console.log('执行类的构造方法');
        this.name = name;
        this.age = age;
    }

    /**
    * 类的一般方法:
    * 相当于定义在实例对象的原型对象上
    * 即若Person为一个构造函数,则类的一般方法相当于 Person.prototype.showMsg
    **/
    showMsg() {
        console.log(this.name, ' & ', this.age);
    }
};
构造函数的形式

继承

// 父类复用上面的Person
// 子类
class childPerson extends Person {
    constructor(name, age, sex) {
        super(name, age); // 调用父类的构造方法
        this.sex = sex;
    }
    // 直接重写一般方法
    showMsg() {
        console.log(this.name, ' & ', this.age, ' & ', this.sex);
    }
}

let child1 = new childPerson('zhangsan', 50, '男');

另:若之前学习的构造函数的继承方式有所遗忘,可参考原型、原型链、及拓展(继承模式)

特点

参考:https://github.com/Advanced-Frontend/Daily-Interview-Question/issues/20

上一篇 下一篇

猜你喜欢

热点阅读