设计模式知识连载(7)---继承_3:优点结合-组合继承
2017-12-12 16:45
351 查看
<body> <h3>设计模式知识连载(7)---继承_3:优点结合-组合继承</h3> <p> 1、在子类构造函数中执行父类构造函数 2、在子类原型上实例化父类 这样就融合了类式继承和构造函数继承的优点,并且过滤了其缺点 </p> <script type="text/javascript"> /** * 组合式继承--案例1: */ // 声明父类 function SuperClass(name) { // 值类型共有属性 this.name = name ; //引用类型共有属性 this.books = ['HTML', 'CSS', 'JavaScript'] ; } // 父类原型共有方法 SuperClass.prototype.getName = function() { console.log(this.name) ; } ; // 声明子类 function SubClass(name, time) { // 构造函数式继承父类name属性 SuperClass.call(this, name) ; // 子类中新增共有属性 this.time = time ; } ; // 类式继承,子类原型继承父类 SubClass.prototype = new SuperClass() ; // 子类原型方法 SubClass.prototype.getTime = function() { console.log(this.time) ; } var subinstance1 = new SubClass('JavaScript入门', 2017) ; var subinstance2 = new SubClass('HTML入门', 2016) ; console.log('subinstance1:', subinstance1) ; console.log('subinstance2:', subinstance2) ; subinstance1.getName(); subinstance1.getTime() ; subinstance2.getName(); subinstance2.getTime() ; // 验证改变其中一个实例是否会影响到另一个实例 subinstance1.books.push('Java') ; console.log('subinstance1.books:', subinstance1.books) ; console.log('subinstance2.books:', subinstance2.books) ; /** * 缺陷: * 在使用构造函数继承时执行了一遍父类的构造函数, * 而在实现子类原型的类继承时又调用了一遍父类的构造函数, * 因此父类构造函数调用了两遍 */ </script> </body>
相关文章推荐
- 设计模式知识连载(24)---组合模式:
- 设计模式知识连载(6)---继承_2:创建即继承-构造函数继承
- 设计模式知识连载(11)---继承_7:多继承
- 设计模式知识连载(9)---继承_5:如虎添翼-寄生式继承
- 设计模式知识连载(5)---继承_1:子类的原型对象-类式继承
- 设计模式知识连载(10)---继承_6:终极继承者-寄生组合式继承
- 设计模式知识连载(29)---策略模式:
- 设计模式知识连载(2)---封装_1
- 设计模式知识连载(12)---调用方式:多态
- [js高手之路]设计模式系列课程-组合模式+寄生组合继承实战新闻列表
- 类继承和对象组合(摘录设计模式)
- 谈谈有关设计模式的思想精髓:变继承关系为组合关系、如何创建对象(单例、状态、装饰者模式)
- 设计模式知识连载(21)---代理模式:
- 设计模式知识连载(26)---模板方法模式:
- 设计模式知识连载(43)---参与者模式:
- 设计模式知识连载(32)---访问者模式:
- 设计模式知识连载(37)---链模式:
- 设计模式知识连载(4)---封装_3:创建对象的安全模式
- 设计模式知识连载(47)---Widget模式:
- 设计模式(2)-策略模式之多用组合少用继承