js的两种继承方式

基于原型的继承:通过隐式原型链来实现继承

// 定义父类Animal
function Animal(sex) {
  this.sex = sex;
}
Animal.prototype.gender = function () {
  console.log(`这只动物是${this.sex}的`);
};
// 让Cat继承Animal
Cat.prototype.__proto__ = Animal.prototype;

// 定义子类Cat
function Cat(sex, food) {
  Animal.call(this, sex); //继承Animal中的sex,相当于super()
  this.food = food;
}
Cat.prototype.eat = function () {
  console.log(`这是只${this.sex}猫,他喜欢吃${this.food}`);
};

let cat = new Cat("公", "🐟");
console.log(cat); // Cat { sex: '公', food: '🐟' }
// 调用Cat中的eat方法
cat.eat(); // 这是只公猫,他喜欢吃🐟
//调用Animal中的gender方法
cat.gender();

基于class的继承:子类通过extends继承父类,通过super继承属性

// 定义父类Animal
class Animal {
  constructor(sex) {
    this.sex = sex;
  }
  gender() {
    console.log(`这只动物是${this.sex}的`);
  }
}
// 定义子类Cat并继承父类Animal
class Cat extends Animal {
  constructor(sex, food) {
    super(sex);
    this.food = food;
  }
  eat() {
    console.log(`这是只${this.sex}猫,他喜欢吃${this.food}`);
  }
}
// 通过Cat实例化一个cat
let cat = new Cat("公", "🐟");
console.log(cat); // Cat { sex: '公', food: '🐟' }
// 调用Cat中的eat方法
cat.eat(); // 这是只公猫,他喜欢吃🐟
// 调用Animal中的gender方法
cat.gender(); // 这只动物是公的
posted @ 2020-12-21 21:33  时光傀儡师  阅读(124)  评论(0编辑  收藏  举报