【发布时间】:2016-07-04 16:59:45
【问题描述】:
下面是一个简单的 JavaScript 继承示例。我们可以替换以下行:Dog.prototype = new Animal();
与 Dog.prototype = Animal.prototype?
我在浏览器中进行了测试,他们给了我相同的结果。我很奇怪为什么我们需要创建一个新的 Animal 对象并将其分配给 Dog.prototype。
function Animal(age){
this.age = age;
}
Animal.prototype.walk = function(){
console.log("Walk");
}
function Dog(color, age){
this.color = color;
Animal.call(this, age)
}
Dog.prototype = new Animal(); //Why not Dog.prototype = Animal.prototype
Dog.prototype.constructor = Dog;
dog_b = new Dog("yellow", 9);
console.log("Age: " + dog_b.age + " Color: " + dog_b.color );
dog_b.walk()
【问题讨论】:
-
"我很奇怪为什么我们需要创建一个新的 Animal 对象" - 直觉很好。你should not use
new Animalthere indeed.
标签: javascript inheritance prototype prototypal-inheritance