js继承方式
2016-12-01 本文已影响0人
_dani
类式继承
function SuperClass(){
this.superValue = 'superValue';
this.langs = ['js','html'];
}
SuperClass.prototype.getSuperValue = function(){
return this.superValue;
}
function SubClass(){
this.subValue = 'subValue';
}
SubClass.prototype = new SuperClass();
SubClass.prototype.getSubValue = function(){
return this.subValue;
}
缺点: 1.父类构造函数中的引用类型会被子类实例共享
2.子类实例化过程中不能将参数传给父类构造函数
构造函数继承
function SuperClass(name){
this.superValue = 'superValue';
this.langs = ['js','html'];
this.name = name || 'super';
}
SuperClass.prototype.getSuperValue = function(){
return this.superValue;
}
function SubClass(name){
this.subValue = 'subValue';
SuperClass.call(this,name);
}
SubClass.prototype.getSubValue = function(){
return this.subValue;
}
优点: 子类实例化过程中可传参给父类构造函数
缺点: 子类不能继承到父类prototype上的属性
组合继承
类式继承 + 构造函数继承
function SuperClass(name){
this.superValue = 'superValue';
this.langs = ['js','html'];
this.name = name || 'super';
}
SuperClass.prototype.getSuperValue = function(){
return this.superValue;
}
function SubClass(name){
this.subValue = 'subValue';
SuperClass.call(this,name);
}
SubClass.prototype = new SuperClass();
SubClass.prototype.getSubValue = function(){
return this.subValue;
}
优点: 1.子类实例中更改继承的引用类型不会影响到其他子类实例
2.子类实例化过程中能将参数传递给父类的构造函数
缺点: 子类继承会调用两次父类构造函数(prototype和call)
原型式继承
function inheritObject(o){
function F(){}
F.prototype = o;
return new F();
}
---
var book = {
name:'langs'
content:['js','html']
}
var newBook = inheritObject(book);
类似于类式继承
缺点:同类式继承
优点:可根据已有对象创建新对象,不必创建自定义的类
寄生式继承
var book = {
name:'langs'
content:['js','html']
}
function createBook(o){
var obj = inheritObject(o);
//扩展新对象
obj.getName = function(){
console.log('name');
}
return obj;
}
在原型式继承的基础上扩展属性
优缺点同原型式继承
寄生组合式继承
寄生式继承 + 构造函数继承
function inheritPrototype(subClass,superClass){
var p = inheritObject(superClass);
p.constructor = subClass;
subClass.prototype = p;
}
function SuperClass(value){
this.superValue = value || 'superValue';
this.langs = ['js','html'];
}
SuperClass.prototype.getSuperValue = function(){
return this.superValue;
}
function SubClass(value){
SuperClass.call(this, value);
}
inheritPrototype(SubClass, SuperClass);
优点:1.子类实例中更改继承的引用类型不会影响到其他子类实例
2.子类实例化过程中可传参给父类构造函数
缺点:代码实现复杂