首页 > 其他 > 详细

Combination Inheritance

时间:2015-05-08 17:51:42      阅读:129      评论:0      收藏:0      [点我收藏+]

  The basic idea is to use prototype chaining to inherit properties and methods on the prototype and to use constructor stealing to inherit instance properties. This allows function reuse by defineing methods on the prototype and allows each instance to have its own properties. Consider the following: 

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);
    this.age = age;
}

SubType.prototype = new SuperType();

SubType.prototype.sayAge = function(){
    alert(this.age);
};

var instance1 = new SubType("Nicholas", 29);
instance1.color.push("black");
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

 

Combination Inheritance

原文:http://www.cnblogs.com/linxd/p/4488381.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!