第一段代码:
function Animal() {}
Animal.prototype.eat = function() {
console.log("nom nom nom");
};
function Dog() {}
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype = {
constructor: Dog,
bark: function() {
console.log("Woof!");
}
};
let beagle = new Dog();
console.clear();
beagle.eat(); // Should print "nom nom nom" but displays a error that eat
//is not a function.
beagle.bark();
第二个代码:
function Animal() {}
Animal.prototype.eat = function() {
console.log("nom nom nom");
};
function Dog() {}
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
Dog.prototype.bark = function() {
console.log("Woof!");
}
let beagle = new Dog();
console.clear();
beagle.eat(); // Prints "nom nom nom"
beagle.bark(); // Prints "Woof!"
beagle.eat()
没有显示正确输出的第一个代码片段有什么问题。
最佳答案
您首先将 Dog
的原型(prototype)分配为 Object.create(Animal.prototype);
,但随后在下一行您完全重新分配 Dog
的原型(prototype)为其他东西,因此继承链不再存在。调整您的第一个代码,您可能只想分配给 Dog.prototype
一次,并使用 Object.assign
和 Object.create
:
function Animal() {}
Animal.prototype.eat = function() {
console.log("nom nom nom");
};
function Dog() {}
Dog.prototype = Object.assign(
Object.create(Animal.prototype),
{
constructor: Dog,
bark: function() {
console.log("Woof!");
}
}
);
let beagle = new Dog();
beagle.eat();
关于javascript - 访问从 child 那里继承的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50826748/