关于类的总结

class Person {
    // 构造器方法
    constructor(name, age){
        this.name = name
        this.age = age
    }
    // 一般方法
    eat(){
        // 方法放在了类的原型对象上,供实例使用
        // 通过Person实例调用eat方法时,eat中的this就是Person实例
        console.log(`我是${this.name},`)
    }
}
// 创建实例
const p1 = new Person('sam', 18)
const p2 = new Person('Tom', 19)


// 创建student类,继承Person类
class Student extends Person {
  // 继承就有了父类的构造器,不需要再写,
  // 如果有新的属性,就要写构造器,并且构造器内必须要用super调用父类的构造器
  constructor(name, age, grade){
    // 调用父类的构造器,必须位于最前面
    super(name, age)
    this.grade = grade
  }
}
// 创建student实例,并新加一个属性
const stu1 = new Student('潮吧', 18, '高二')

posted @ 2024-03-08 21:52  幻影之舞  阅读(9)  评论(0)    收藏  举报