function Animal(name) {
this.name = name;
}
Animal.prototype.printName = function() {
console.log(`my name is ${this.name}`)
}
function Dog(name) {
Animal.call(this, name);
this.speak = () => console.log('woof');
}
Dog.prototype = Animal.prototype // <=== **this line here**
Dog.prototype.constructor = Dog
const leo = new Dog('leo')
leo.speak()
leo.printName()
Dog.prototype = Animal.prototype
和 Dog.prototype = Object.create(Animal.prototype)
有什么区别还是一样?
除了 mplungjan 的评论之外。 您可以使用更明确的
Object.setPrototypeOf()
来控制原型继承。
另外,您不需要分配 Dog 的构造函数,它已经完成了。
function Animal(name) {
this.name = name;
}
Animal.prototype.printName = function() {
console.log(`my name is ${this.name}`)
}
function Dog(name) {
Animal.call(this, name);
}
Dog.prototype.speak = () => console.log('woof');
Object.setPrototypeOf(Dog.prototype, Animal.prototype);
// Dog.prototype.constructor = Dog - you don't need this, it's already done by Dog the definition
console.log(Dog.prototype.constructor);
const leo = new Dog('leo')
leo.speak()
leo.printName()