【发布时间】:2013-04-27 02:53:51
【问题描述】:
为什么这里说“动物”而不是“小猫”?
// create base class Animal
function Animal(animalType) {
this.type = animalType;
this.sayType = function () {
alert(this.type);
};
}
// create derived class Cat
function Cat(myName) {
Animal.call(this, "cat"); // cat calls the Animal base class constructor
this.name = myName;
this.sayName = function () {
alert(this.name);
};
}
Cat.prototype = Object.create(Animal); // set Cat's prototype to Animal
// instantiate a new instance of Cat
var cat = new Cat("kitty");
cat.sayName();
cat.name = "lol";
cat.sayName();
【问题讨论】:
-
您的
sayType和sayName函数实际上并未使用原型继承因为它们不在原型上!您已将它们创建为实例本地属性。
标签: javascript inheritance prototype