寄生组合继承例子

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());

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值