JS基础 - HopeXKelvin/HopeXKelvin.github.io GitHub Wiki

原型继承

示例:

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

var dog = new Animal('dog', 'mammal');

// 给 Animal 原型添加一个shout方法
Animal.prototype.shout = function(){
    console.log(this.name + ' is ' + this.sound + 'ing...');
}

// 定一个Dog方法,继承Animal,并且添加一个自己的属性,sound
function Dog(name, type) {
    Animal.call(this, name, type);// 通过call来进行this的变换
    this.sound = 'bow';
}

// 验证
let pet = Dog('germanShepard', 'mammal');
console.log(pet);// return Dog {name: '', type: '', shout: ''}
pet.shout();// 报错, 因为Dog 并没有继承父类的方法

// 可以通过指向原型的方式去解决这个问题
Dog.prototype = Object.create(Animal.prototype);
let pet2 = Dog('yellow_dog', 'mammal');
pet2.shout();// yellow_dog is bowing...

四点要注意的地方:

  • class的属性是通过this来绑定的
  • class的方法是通过使用 prototype原型对象来进行绑定的
  • 为了继承属性,使用call方法来传this的值
  • 为了继承方法,使用Object.create去连接parent和child
  • 始终需要将child的构造函数设置成自身,为了能够正确识别出所属类型