构造函数和继承的几种实现
构造函数
1.组合使用构造函数模式和原型模式
组合使用构造函数模式和原型模式即在构造函数中定义实例属性,在原型中定义方法和共享的属性。
function Person(name,age)
{
this.name=name;
this.age=age;
this.friends=["shelby","Court"];
}
Person.prototype={
constructor:Person,
sayName:function(){
console.log(this.name)
}
}
var instance=new Person("Niko",45);
instance.sayName();
2.动态原型模式
动态原型模式将原型初始化放到了构造函数中,看上去更整体了些。同时对原型是否已经初始化进行了判断,避免了重复初始化。
function Person(name,age)
{
this.name=name;
this.age=age;
this.friends=["shelby","Court"];
if(typeof this.sayName!="function"){
Person.prototype.sayName=function(){
console.log(this.name);
}
}
}
var instance=new Person("Niko",45);
instance.sayName();
继承
1.组合继承
组合继承即使用原型链实现对原型属性和方法的继承,用借用构造函数实现对实例属性的继承。
function SuperType(name){
this.name=name;
this.colors=["red","blue","green"];
}
SuperType.prototype.sayName=function(){
console.log(this.name);
}
function SubType(name,age){
SuperType.call(this,name); //借用构造函数
this.age=age;
}
SubType.prototype=new SuperType("super"); //原型链
var instance=new SubType("Niko",43);
instance.sayName();
2.寄生组合式继承
寄生组合式继承是通过借用构造函数继承属性,通过原型链的混成形式继承方法。
function object(o){
function F(){}
F.prototype=o;
return new F();
}
function inheritPrototype(subType,superType){
var p=object(superType.prototype);
p.constructor=subType;
subType.prototype=p;
}
function SuperType(name){
this.name=name;
this.colors=["red","blue","green"];
}
SuperType.prototype.sayName=function(){
console.log(this.name);
}
function SubType(name,age){
SuperType.call(this,name);
this.age=age;
}
inheritPrototype(SubType,SuperType);
var instance=new SubType("Niko",43);
instance.sayName();