【发布时间】:2014-08-13 04:03:57
【问题描述】:
在 codecademy 中学习 JS,对第 18/30 课有关继承的一些技术问题感到困惑。
企鹅是动物的子类。
我将 Penguin 的原型设置为 Animal,并在 Penguin 构造函数中指定了它的 numLegs。但是,我没有指定它的名称和食物,它们是 Animal 类的属性。
Penguin 构造函数只接受 1 个参数 name,而 Animal 构造函数接受 3 个参数:name、food 和 numLegs。
如果我创建一个名为“Bob”的新企鹅对象,例如,它的 numLegs 和 food 将是什么?
// the original Animal class and sayName method
function Animal(name, numLegs, food) {
this.name = name;
this.numLegs = numLegs;
this.food = food;
}
Animal.prototype.sayName = function() {
console.log("Hi my name is " + this.name);
};
// define a Penguin class
function Penguin(name)
{
this.numLegs=2;
this.name=name;
}
// set its prototype to be a new instance of Animal
Penguin.prototype=new Animal();
【问题讨论】: