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());
寄生组合继承例子
最新推荐文章于 2022-11-28 10:45:59 发布