ES5和ES6的继承

发布时间 2023-11-24 16:20:56作者: _尼欧`

ES5继承

function Animal(name) {
  this.name = name;
}

Animal.prototype.sayName = function() {
  console.log('My name is ' + this.name);
};

function Dog(name) {
  // 把子类的 this 传入父类并执行父类函数,此时子类的 this 已有 name 属性
  Animal.call(this, name);
}
// Animal.prototype 是一个对象并且有 sayName 属性
Dog.prototype = Object.create(Animal.prototype);
// 正常来说函数的 prototype.constructor 属性指向函数本身,
// 则 Dog.prototype.constructor === Dog is true
// 上一行代码使 Dog.prototype.constructor === Animal is true,
// 所以要把 Dog.prototype.constructor 再次指向 Dog 函数本身
Dog.prototype.constructor = Dog;
// 在使用 new 关键字时会 调用 Dog.prototype.constructor
var dog = new Dog('Tom');
dog.sayName(); // My name is Tom

ES5继承引入了 class 关键字

class Animal {
  constructor(name) {
    this.name = name;
  }

  sayName() {
    console.log(`My name is ${this.name}`);
  }
}

class Dog extends Animal {
  constructor(name) {
    super(name);
  }
}

let dog = new Dog('Tom');
dog.sayName(); // My name is Tom

在子类 Dog 中 super 函数不能省略,否则会报错,实际是调用父类的 constructor 函数,并把 Dog 的 this 传入父类此时的父类 this.name = name 的 this 指向的是子类 Dog
ES6 和 ES5 本质是一样