javascript继承学习系列之四:组合继承(Combination Inheritance)
2011-07-06 13:28
447 查看
它结合了原型链和对象伪装各自优点的方式。它的基本思路是使用原型链继承原型上的属性和方法,使用对象伪装继承实例属性。通过定义原型方法,允许函数复用,并允许每个实例拥有它们自己的属性。参考以下代码:
function BaseClass(name)
{
this.name = name;
this.colors = ["red","blue"];
}
BaseClass.prototype.getName = function(){return this.name;}
function ChildClass(name,age)
{
// inherit
BaseClass.call(this,name);
this.age = age;
}
// inherit
ChildClass.prototype = new BaseClass();
ChildClass.prototype.getAge = function(){return this.age;}
var instance1 = new ChildClass("sds1",28);
var instance2 = new ChildClass("sds2",29);
instance2.colors.push("green");
var instance3 = new ChildClass("sds3",30);
alert(instance1.colors);//red,blue
alert(instance1.getName());//sds1
alert(instance1.getAge());//28
alert(instance2.colors);//red,blue,green
alert(instance2.getName());//sds2
alert(instance2.getAge());//29
alert(instance3.colors);//red,blue
alert(instance3.getName());//sds3
alert(instance3.getAge());//30
原型链和对象伪装的继承,它们各自有优缺点,并且是互补的,而组合继承正是利用了它们的这种互补性将其结合在一起,比较完美的实现了继承。通过上面的示
例,清楚的看到同时通过组合的方式ChildClass继承了BaseClass类,ChildClass类的三个实例的属性各不影响,且方法都是可复用
的原型方法。
组合继承的本质还是原型链和对象伪装。
function BaseClass(name)
{
this.name = name;
this.colors = ["red","blue"];
}
BaseClass.prototype.getName = function(){return this.name;}
function ChildClass(name,age)
{
// inherit
BaseClass.call(this,name);
this.age = age;
}
// inherit
ChildClass.prototype = new BaseClass();
ChildClass.prototype.getAge = function(){return this.age;}
var instance1 = new ChildClass("sds1",28);
var instance2 = new ChildClass("sds2",29);
instance2.colors.push("green");
var instance3 = new ChildClass("sds3",30);
alert(instance1.colors);//red,blue
alert(instance1.getName());//sds1
alert(instance1.getAge());//28
alert(instance2.colors);//red,blue,green
alert(instance2.getName());//sds2
alert(instance2.getAge());//29
alert(instance3.colors);//red,blue
alert(instance3.getName());//sds3
alert(instance3.getAge());//30
原型链和对象伪装的继承,它们各自有优缺点,并且是互补的,而组合继承正是利用了它们的这种互补性将其结合在一起,比较完美的实现了继承。通过上面的示
例,清楚的看到同时通过组合的方式ChildClass继承了BaseClass类,ChildClass类的三个实例的属性各不影响,且方法都是可复用
的原型方法。
组合继承的本质还是原型链和对象伪装。
相关文章推荐
- JS学习笔记——JavaScript继承的6种方法(原型链、借用构造函数、组合、原型式、寄生式、寄生组合式)
- JavaScript学习系列之深入原型链与继承的实现
- javascript继承学习系列之一:初识JS的OOP
- javascript继承学习系列之三:对象伪装(Object Masquerading)
- javascript继承学习系列之二:原型链(Prototype Chaining)
- javascript继承学习系列之五:其他方式
- 【JavaScript学习】面向对象的程序设计(5):组合继承(伪经典继承)
- 【JavaScript学习】面向对象的程序设计(7):寄生式继承和寄生组合式继承
- 学习javascript基础知识系列第三节 - ()()用法
- Javascript学习之6种常用继承方式详解
- Javascript 设计模式学习笔记(2) - 继承(Inheritance) (下)
- 深入理解JavaScript系列(40):设计模式之组合模式
- 深入理解JavaScript系列(二): 原型、原型链与继承
- html5学习笔记---05.JavaScript 中的面向对象,继承和封装
- Effective C++学习系列之继承关系
- 《JavaScript 语言精粹》 学习笔记 —— 第五章 继承
- JavaScript继承学习笔记【新手必看】
- Javascript学习笔记2 继承 原型链
- Javascript学习笔记(Object 对象与继承)
- 从面试题学习Javascript——面向对象(继承)