JS之继承(摘自高程)
原型链
function SuperType(){ } SuperType.prototype.name="name"; SuperType.prototype.sayName= function () { return this.name; }; function SubType(){ } SubType.prototype=new SuperType(); //将SuperType函数的实例赋给SubType函数的原型,改变了SubType函数的原型 var obj=new SubType(); alert(obj.sayName());
原型继承的缺点:
1、最主要的问题是来自包含引用类型值的原型
function SuperType(){ this.colors=["red","blue","green"]; } function SubType(){ } SubType.prototype=new SuperType(); var instance1=new SubType(); instance1.colors.push("black"); alert(instance1.colors); //"red","blue","green","black" var instance2=new SubType(); alert(instance2.colors); //"red","blue","green","black"
第二个问题:没法在不影响所有对象实例的情况下,给超类型的构造函数传递参数
借用构造函数 ( 在超类型的原型中定义的方法,对子类型而言也是不可见的 )
function SuperType(name){
this.name=name;
}
function SubType(name){
SuperType.call(this,"lily");
}
var instance1=new SubType();
console.log(instance1.name);
缺点:构造函数的诟病,无法复用函数
组合继承
function SuperType(name){ this.name=name; this.colors=["red","blue","green"]; } SuperType.prototype.sayName= function () { return this.name; }; function SubType(name,age){ SuperType.call(this,name); this.age=age; } SubType.prototype=new SuperType(); SubType.prototype.constructor=SubType; SubType.prototype.sayAge= function () { return this.age; }; var instance=new SubType("lily",25); instance.colors.push("black"); console.log(instance.colors); console.log(instance.sayAge()); console.log(instance.sayName()); var instanceAgain=new SubType("lucy",26); console.log(instanceAgain.colors); console.log(instanceAgain.sayAge()); console.log(instanceAgain.sayName());
原型式继承
function object(o){ function F(){} F.prototype=o; return new F(); } var person={ name:"lily", friend:["lucy","fang"] }; var newPerson=object(person); var person1=newPerson.friend; var newFriend=person1.push("feng"); console.log(person1); var newPerson02=object(person); var person2=newPerson02.friend; console.log(person2)
寄生式继承
function object(person){ function F(){} F.prototype=person; return new F(); } function createAnother(original) { var clone=object(original); clone.sayHi= function () { alert("hi"); }; console.log(clone); return clone; } var person={ name:"lily", friends:["fang","feng"] }; var anotherPerson=createAnother(person); anotherPerson.sayHi(); console.log(person);
缺点:不能做到函数复用而降低效率,与构造函数模式类似
寄生组合式继承(inheritPrototype(子类型构造函数,父类型构造函数))
function object(obj){ function F() { } F.prototype=obj; return new F(); } function inheritPrototype(SubType,SuperType){ var inherit=object(SuperType.prototype); inherit.constructor=SubType; SubType.prototype=inherit; return inherit; } function SuperType(name){ this.name=name; } SuperType.prototype.sayName=function(){ alert(this.name); }; function SubType(name,age){ SuperType.call(this,name); this.age=age; } inheritPrototype(SubType,SuperType); SubType.prototype.sayAge= function () { alert(this.age); }; var person=new SubType("lily",25); person.sayAge(); person.sayName();
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。