// 通过原型的方式实现动物类继承,
// 动物都有性别和年龄,有吃东西的行为,狗都有毛色,有看家的行为。
// 要求实例化狗对象,并调用吃和看家的方法
function Animal(gender,age){ this.gender = gender; this.age = age; } Animal.prototype.eat = function(){ console.log('会吃东西'); } function Dog(gender,age,color){ this.gender = gender; this.age = age; this.color = color; } //原型替换,将狗的原型替换成动物的实例 Dog.prototype = new Animal(); Dog.prototype.lookHouse = function() { console.log('会看家'); } var dog = new Dog('公','2','color'); console.log(dog); dog.eat(); dog.lookHouse();
结合完整的原型链去理解会更容易理解,附图