类的基本知识整理

149 阅读1分钟

1632813326(1).png

// 创建一个类
class Person {
    // 类中可以直接写赋值语句,以下代码的含义是:给Person的实例对象添加一个属性,名为:a,值为:1
    a = 1
    // static 表示给类自身 加一个demo属性
    static demo = 1
    // 构造器方法
    constructor(name, age) {
        // 构造器中的this是-- 类的实例对象
        this.name = name
        this.age = age
    }
    // 一般方法, 放在了类的原型对象上,供实例使用,通过Person实例调用speak时,speak中的this是类的实例对象
    speak () {
        console.log(`${this.name}`)
    }
}
// 创建一个 Student 类,继承于Person
class Student extentds Person {
    // 构造器 继承Person 的 构造器可不写,但如果Student所独有属性是必须写
    constructor(name, age, grade) {
        // 帮你调用父类的构造器,必须写在Student的所有属性之前
        // 其相当于(但不能这么写,会报错):
        // this.name = name
        // this.age = age
        super(name, age)
        this.grade = grade
        this.school = '潇潇' // 所有Student的实例上都有这个
    }
    // 重写从父类继承过来的方法
    speak () {
        console.log(`${this.name}`)
    }
}
// 创建一个实例
new Person('张三', 123)
new Student('李四', 123, '高一')