您的位置:首页 > Web前端 > JavaScript

JavaScript继承方式

2017-04-03 15:24 274 查看
摘自《Javascript高级程序设计(第三版)

很多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();


寄生组合继承是最理想的引用类型继承方式。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: