理解js 继承

71 阅读1分钟

继承 对于js 来说, 我自己没有的方法和属性, 我要想办法去拿别人的属性和方法, 来给我自己去使用, 下面使用 es6 新增的 class 来理解一下继承

1.本质上构造函数只是函数而已,并不是真正的类
2.用class定义一个类,对象中会包含一个constructor方法,相当于一个构造函数,也称为构造器,在其中子类可以用super()函数调用父类的构造方法
4.类中也可以定义一般的方法,相当于构造函数.prototype去定义方法

class 实现继承

class Student {
  constructor(name, age) {
    this.name = name
    this.age = age
  }
  study() {
    console.log('学习')
  }
}

class CollegeStu extends Student {
  constructor(name, age, school) {
    super(name,age) // 调用父类的构造函数和方法 ,这里相当于调用 student constructor
    this.school = school
  }
  say() {
    console.log(`我的名字${this.name}, 我的年龄: ${this.age}, 我在${this.school}上学`)
  }
}

let student = new Student('小明', 20)
student.study() // 学习

let collegeStu = new CollegeStu('小华', 21, '清华大学')
collegeStu.study() // 使用extends 继承Student 上的 study() 方法 
collegeStu.say() // 使用自己的方法