带有原型冗余对象的javascript继承
javascript inheritance with prototype - redundant object
我正在阅读一篇关于JavaScript中继承的教程,其中有以下语句:
Rabbit类的对象要从Animal类继承,我们需要:
- 定义动物
- 定义Rabbit
-
从动物身上继承兔子:
Rabbit.prototype=新动画()
他们说,这种方法的缺点是需要创建一个冗余对象。我不明白为什么我需要创建那个多余的对象?我尝试了以下操作,它在不创建冗余对象的情况下工作:
function Animal() {};
function Rabbit() {};
Rabbit.prototype = Animal.prototype
Animal.prototype.go = function() {alert("I'm inherited method"};
var r = new Rabbit();
r.go();
我在这里错过了什么?
您缺少的是,在您的代码中,Rabbit
和Animal
共享完全相同的原型。如果您将eatCarrot
方法添加到Rabbit
,那么每隔一个Animal
也会有该方法。
你使用的教程实际上有些过时了。子类化的首选方法是使用Object.create
为Rabbit创建一个全新的prototype
对象,该对象链接到Animal.prototype
:
Rabbit.prototype = Object.create(Animal.prototype);
Rabbit.prototype.constructor = Rabbit;
请注意,这并不依赖于从Animal
的实例中对Rabbit
进行子类化。
有关详细信息,请参阅MDN。
您的方法有一个严重的缺陷,最好通过一个例子来证明:
function Animal() {};
Animal.prototype.feed = function(){
console.log("feeding")
};
function Rabbit() {this.teeth = 4};
Rabbit.prototype = Animal.prototype; // oops
Rabbit.prototype.feed = function(){
if(this.teeth > 1){
console.log("chewing")
} else {
throw "I have no teeth!"
}
}
var leechworm = new Animal;
leechworm.feed(); //throws
由于leechworm
是Animal
,无论我们定义什么种类的动物,它都应该能够喂养,但由于Animal.prototype === Rabbit.prototype
,Animal.prototype.feed
与Rabbit.prototype.feed
相同。水蛭会抱怨他没有牙齿。
相关文章:
- 关于Javascript继承,我可以'我不明白
- Javascript继承代码集
- Javascript:继承原型而不重新定义构造函数
- JavaScript继承:未捕获的范围错误:超过了最大调用堆栈大小
- JavaScript继承:为什么从实例复制
- javascript继承中正确的原型做作是什么
- 没有原型的Javascript继承
- Javascript继承-使用.call方法
- 运行Javascript继承代码时出错
- Javascript继承构造函数
- Javascript继承和封装,高效完成
- 具有简洁原型赋值语法的Javascript继承
- Javascript继承的问题&基类原型
- JavaScript继承构造函数.prototype
- javascript继承说明
- Javascript继承:从超类的方法设置子类的属性
- 简单的 Javascript 继承示例
- 具有意外行为的 JavaScript 继承
- 基于实例的 JavaScript 继承
- 为什么 JavaScript 继承是这样工作的