Chr*_*isR 17 javascript prototype
我一直想知道,因为我学习了原型继承,为什么要将父类的实例推送到子原型而不是原型本身?
var Animal = function(type){
this.type = type;
}
Animal.prototype.getType = function(){
return this.type;
}
var Cat = function(options){
this.breed = options.breed;
}
//Inheritance
Cat.prototype = new Animal('Cat');
Run Code Online (Sandbox Code Playgroud)
为什么不这样做继承呢?
Cat.prototype = Animal.prototype;
Run Code Online (Sandbox Code Playgroud)
我的猜测是,只继承原型,你不包括在构造函数(this.type)中创建的属性,但我不完全确定.有人想开导我吗?
但是,不是将一个实例放入子类原型中,而是将所有构造函数定义的属性放入原型中,从而引入可能的陷阱?我正在考虑这样一个事实:除非在构造函数中定义了原型属性,否则它们将在类的所有实例之间共享.
And*_*yle 18
好吧,如果不考虑它,如果采用后一种方法,原型链实际上就不会持有.例如,让我们假设Animal继承自Entity.然后Animal.prototype将某些类型的指针指向的Entity-然后
Cat.prototype = Animal.prototype;
Run Code Online (Sandbox Code Playgroud)
将Cat的原型设置为与Animal 相同的原型(即一些实体参考).这将使猫成为动物的兄弟,而不是像预期的那样的孩子.
因此,为了正确建立原型链,必须使用父类的实例,以便能够获取该类的属性.
| 归档时间: |
|
| 查看次数: |
966 次 |
| 最近记录: |