我们需要实现如下需求:

  1. function Parent(){}
  2. Parent.prototype.name = '父name'
  3. function Child(){}
  4. Child.prototype.age = '子age'
  5. const childInstance = new Child()
  6. // 存在父类和子类,子类的实例要同时拥有两个类的原型上的属性和方法。
  7. childInstance.name === '父name'
  8. childInstance.age === '子age'

那么要怎么实现类的继承呢?有几种实现的方法?

ES6 class 继承

先熟悉一下 class 语法:

  1. class Person {
  2. constructor() {
  3. // 添加到 this 的所有内容都会存在于不同的实例上
  4. this.locate = () => console.log("instance", this);
  5. }
  6. // 定义在类的原型对象上
  7. locate() {
  8. console.log("prototype", this);
  9. }
  10. // 定义在类本身上
  11. static locate() {
  12. console.log("class", this);
  13. }
  14. }

使用 class 继承:

  1. // 1. 创建父类
  2. class Parent {
  3. constructor(name) {
  4. this.name = name
  5. }
  6. eat(food) {
  7. console.log(`${this.name}正在吃:${food}`)
  8. }
  9. }
  10. // 2. 创建子类 - 继承
  11. class Child extends Parent {
  12. constructor(name, age) {
  13. super(name)
  14. this.age = age
  15. }
  16. intro() {
  17. console.log(`${this.name}今年${this.age}岁了`)
  18. }
  19. }
  20. const child = new Child('小明', 16)
  21. child.eat('牛肉')
  22. child.intro()