Javascript 杂质与原型继承
让我们有两个构造函数Javascript 杂质与原型继承,javascript,Javascript,让我们有两个构造函数 bird= function(name){ this.cry=function(){ alert('cry'); } this.name=name; } duck= function(){ this.cry=function(){ alert('cry cry'); } } b= new bird('Ivan'); d= duck.call(b); 并考虑原型继承< /P> bird= function(name){ this.cry=fu
bird= function(name){
this.cry=function(){ alert('cry'); }
this.name=name;
}
duck= function(){
this.cry=function(){ alert('cry cry'); }
}
b= new bird('Ivan');
d= duck.call(b);
并考虑原型继承< /P>
bird= function(name){
this.cry=function(){ alert('cry'); }
this.name=name;
}
duck= function(){
this.cry=function{ alert('cry cry'); }
}
duck.prototype= new bird('Ivan');
当原型继承优于原型继承时,以及当原型继承优于原型继承时,您可以获得一个示例。您不应该创建父实例来设置继承的原型部分(使用Child.prototype=Object.create(Parent.prototype);Child.prototype.constructor=Child) 构造函数应该以大写字母(大写字母)开头 您可以通过在构造函数(第一个示例)函数和子do
Parent.apply(这是参数)中填充所有内容来继承
但是Child将无法扩展父函数,并且将需要更多的cpu和内存来创建Child和Parent的实例
第二个示例使用prototype的方式是错误的,您将共享行为设置为实例成员(cry函数)和Duck prototype上的实例特定成员(name成员)。与您提供的第一个示例相比,使用prototype(如果操作正确)的优势是:
可以找到有关构造函数和原型的更多详细信息。在第一个示例中,根本没有继承。您只需使用
duck.call(b)
调用构造函数作为函数,将bird的实例绑定为this
,并覆盖“b”实例的现有方法。FYI变量d
在您的情况下无效。可能重复