Pra*_*ena 1 javascript inheritance
第一个代码:
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();Run Code Online (Sandbox Code Playgroud)
第二个代码:
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!"Run Code Online (Sandbox Code Playgroud)
第一个beagle.eat()没有显示正确输出的代码片段有什么问题.
你是第一次分配Dog原型Object.create(Animal.prototype);,但是在下一行你完全将 Dog原型重新分配给其他东西,所以继承链不再存在.调整您的第一个代码,您可能只想分配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();Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
37 次 |
| 最近记录: |