JavaScript继承方式
2017-04-03 15:24
274 查看
摘自《Javascript高级程序设计(第三版)
很多OO语言支持两种继承方式:接口继承,实现继承。Javascript仅支持实现继承,而且其实现继承主要依靠原型链来实现的。
原型链继承
实现原型链继承的基本方式
两个弊端:引用类型被所有实例共享;不能向超类型构造函数中传参
借用构造函数
弊端: 方法在函数中定义,不可复用;超类原型中定义的方法对子类不可见
组合继承
融合了原型链和借用构造函数的优点
原型式继承
object的标准化函数:Object.create();
同样存在引用类型共享的问题
寄生式继承
寄生组合继承
前面组合继承中,超类的构造函数会被调用两次
寄生组合继承是最理想的引用类型继承方式。
很多OO语言支持两种继承方式:接口继承,实现继承。Javascript仅支持实现继承,而且其实现继承主要依靠原型链来实现的。
原型链继承
实现原型链继承的基本方式
function superType(){ //属性 this.color=['blue','green','red'];//弊端:使用原型链继承color将被所有实例共享 } function subType(){ //属性 } //继承superType subType.prototype=new superType();
两个弊端:引用类型被所有实例共享;不能向超类型构造函数中传参
借用构造函数
function superType(name){ this.name=name; } function subType(name){ superType.call(this,name);//继承了superType,同时传递了参数; this.age=24; }
弊端: 方法在函数中定义,不可复用;超类原型中定义的方法对子类不可见
组合继承
function superType(name){ this.name=name; } superType.prototype.sayName=function(){ alert(this.name); } function subType(name){ superType.call(this,name);//继承了superType,同时传递了参数;第二次调用super this.age=24; } subType.prototype=new superType();//原型链继承 第一次调用super sub.prototype.sayAge=function(){ alert(this.age); }
融合了原型链和借用构造函数的优点
原型式继承
function object(o){ function F(){}; F.prototype=o; return new F(); }
object的标准化函数:Object.create();
同样存在引用类型共享的问题
寄生式继承
function createAnother(o){ var clone=Object.create(o); clone.sayHello(){ alert('hello'); } }
寄生组合继承
前面组合继承中,超类的构造函数会被调用两次
function inheritProtoType(superType,subType){ var protoType=Object.create(superType.prototype); protoType.constructor=subType; subType.prototype=protoType; } function superType(name){ this.name=name; this.color=['blue','red','green'] } superType.prototype.sayName=function(){ console.log(this.name); } function subType(name,age){ superType.call(this,name); this.age=age; } inheritProtoType(superType,subType); subType.prototype.sayAge=function(){ console.log(this.age); } ins1=new subType('Lilei',25); ins2=new subType('Hanmei',24); console.log(ins1); ins1.sayName(); ins1.sayAge(); ins2.sayName(); ins2.sayAge();
寄生组合继承是最理想的引用类型继承方式。
相关文章推荐
- JavaScript继承实现方式一览
- JavaScript继承实现方式一览 - winter-cn - 博客园
- JavaScript面向对象的继承机制实现方式
- JavaScript继承方式(1)
- javascript面向对象继承方式分享
- javascript 继承实现方式
- javascript学习笔记(九)javascript中的原型(prototype)及原型链的继承方式
- javascript继承方式之二
- javascript继承方式之一
- JavaScript继承方式(3)
- JavaScript笔记 - 对象继承的几种方式
- javascript实现继承的多种方式
- 演示OOP中的封装、继承在JavaScript中的书写方式(另附JS反射的例子)
- javascript继承方式之三
- 实现JavaScript中继承的三种方式
- javascript的几种继承方式
- 面向对象的JavaScript 六 ---- javascript 继承方式总结
- 实现JavaScript中继承的三种方式
- JavaScript继承方式实例
- JavaScript继承方式(4)