码迷,mamicode.com
首页 > 其他好文 > 详细

Combination Inheritance

时间:2015-05-08 17:52:50      阅读:115      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!