javascript寄生组合式继承

  下面是javascript寄生组合式继承源代码,选自这里。讲解请见我所加注释:

function creatObject(o){//该函数是为了创建原型链对象所用,传入值o为一个function F(){}//新建函数
F.prototype = o;//设置该函数的原型属性为传入对象
return new F();//调用该函数后返回链式对象F.prototype=o;
}

function inheritPrototype(subType, superType){//用于设置对象属性
var prototype = creatObject(superType.prototype);   //创建对象相当于F.prototype=superType.prototype。注意此时var prototype存储为F对象
prototype.constructor = subType;   //设置重写原型后的constructor:相当于F.constructor=subType
subType.prototype = prototype; //设置subType原型:subType.prototype=F
}

function SuperType(name){//该函数是构造项,主要用于生成对象时变量的继承
this.name = name;
this.colors = ["red", "blue", "green"];
}
SuperType.prototype.sayName = function(){
alert(this.name);
};
function SubType(name, age){//直接生成对象时的超类
SuperType.call(this, name);//调用superType函数,设置name,colors[],sayName()属性。
this.age = age;//直接设置age属性
}
inheritPrototype(SubType, SuperType);//调用函数,设置值,代码见上。未生成变量即完成设置
SubType.prototype.sayAge = function(){//添加sayAge()属性。
alert(this.age);
};
var instance1 = new SubType("Nicholas", 29);//新建变量,调用SubType() 构造器构造属性,其中调用SuperType()完成一系列继承变量初始化。
instance1.colors.push("black");//此时colors属性为专有,因为其并未设置在原型中,而是通过SuperType()函数设置的。
alert(instance1.colors);  //"red,blue,green,black"//后面神马的作对比的无关紧要了。
instance1.sayName();  //"Nicholas";
instance1.sayAge();   //29
   
var instance2 = new SubType("Greg", 27);
alert(instance2.colors);  //"red,blue,green"
instance2.sayName();  //"Greg"
instance2.sayAge();//  27

  好了,组合寄生式继承就像这个样子了。

posted @ 2015-01-30 18:01  小北先森  阅读(141)  评论(0编辑  收藏  举报