<script>
function Animal(name) {
this.name = name
}
Animal.prototype.eat = function () {
console.log(this.name + ' is eating');
}
function Dog(name, breed) {
// Function 实例的call()方法会以给定的 this 值和逐个提供的参数调用该函数
// this 是 Dog 构造函数实例化对象,然后执行构造函数 (this.name=name)
Animal.call(this, name)
this.breed = breed
}
// 建立原型链,让 Dog 继承Animal
Dog.prototype = new Animal()
// 让原型对象指回Dog
Dog.prototype.constructor = Dog
Dog.prototype.bark = function () {
console.log(this.name + ' is barking');
}
const dog = new Dog('Buddy', 'Labrador')
console.log(dog);
dog.eat()
dog.bark()
</script>
运行结果如下:
Dog构造函数的原型对象指向Animal实例化的一个对象,通过constructor属性又将该原型对象的构造函数指回了Dog,接着给Dog的原型对象上添加了bark()方法。Dog的原型对象Animal也有一个原型对象Object,该原型对象上又挂载了一个eat()方法。所以通过实例化Dog对象可以调用eat()和bark()方法。