您的位置:首页 > 其它

寄生组合继承例子

2016-03-20 20:15 316 查看
function inheritPrototype(subClass, superClass) {
function F(){}
F.prototype = superClass.prototype;
var prototype = new F();
prototype.constructor = subClass;
subClass.prototype = prototype;
}
function SuperType() {
this.superTypeValue = 0;
this.colors = ["r", "g"];
console.log("111111111111");
}

SuperType.prototype.getSuperTypeValue = function(){
console.log("SuperType.prototype.getSuperTypeValue");
return this.superTypeValue;
}

function SubType() {
SuperType.call(this);
this.subTypeValue = 3;
console.log("2222222222222");
}

inheritPrototype(SubType, SuperType);

SubType.prototype.getSuperTypeValue = function() {
var tmpNum = SuperType.prototype.getSuperTypeValue.call(this);
console.log("SubType.prototype.getSuperTypeValue tmpNum:"+tmpNum);
return tmpNum + 10000;
}

SubType.prototype.getSubTypeValue = function(){
return this.subTypeValue;
}

//SubType.prototype.getSuperTypeValue = function() {
//    return this.superTypeValue + 2;
//}

function ThirdType() {
SubType.call(this);
this.thirdTypeValue = 0;
console.log("333333333333")
}

inheritPrototype(ThirdType, SubType);

ThirdType.prototype.getSuperTypeValue = function() {
var tmpNum = SubType.prototype.getSuperTypeValue.call(this);
console.log("ThirdType.prototype.getSuperTypeValue tmpNum:"+tmpNum);
return tmpNum+100;
}

ThirdType.prototype.getSubTypeValue = function() {
var tmpNum = SubType.prototype.getSubTypeValue.call(this);
console.log("ThirdType.prototype.getSubTypeValue tmpNum:"+tmpNum)
return tmpNum + 100;
}

var subType = new SubType();
subType.superTypeValue = 1;
subType.colors.push("b");
console.log("subType superTypeValue: "+subType.getSuperTypeValue());
console.log("colors:"+subType.colors);

var subType2 = new SubType();
console.log("subType2 superTypeValue: "+subType2.getSuperTypeValue());
console.log("colors:"+subType2.colors);

var thirdType = new ThirdType();
thirdType.superTypeValue = 10;
thirdType.subTypeValue = 10;
console.log("thirdType superTypeValue:"+thirdType.getSuperTypeValue());
console.log("subTypeValue1:"+thirdType.getSubTypeValue());

var thirdType2 = new ThirdType();
thirdType.superTypeValue = 20;
thirdType2.subTypeValue = 20;
console.log("thirdType2 superTypeValue:"+thirdType.getSuperTypeValue());
console.log("subTypeValue2:"+thirdType2.getSubTypeValue());
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: