JS继承方法详解以及优缺点

2020-02-26  本文已影响0人  匿于烟火中

前置阅读:理解原型、new、构造函数

构造函数直接实现


function SuperType(){
    this.property =true;
}

function SubType(){
      SuperType.call(this);
}

//修改父类上的原型内容
SuperType.prototype.getType = function(){
    return 'add';
}
var instance = new SubType();

console.log(instance.property);
//true
console.log(instance.getType());
//报错:Uncaught TypeError: instance.getType is not a function

原型继承


function SuperType(){
    this.property =true;
    this.colors = ['red','green'];
}
SuperType.prototype.getSuperValue = function(){
    return this.property;
}

var parent = new SuperType();
function SubType(){
    this.property = false;//子类重写父类属性
}
//把子类的原型设置为父类的一个新的实例对象
//父类的实例的__proto__中指向它自己的原型对象
//所以这样子类也可以成功访问到
SubType.prototype = new SuperType(); 
SubType.prototype.getSubType = function(){
    return this.property;
}
var instance = new SubType();
console.log(instance.getSuperValue());//false
instance.colors.push('blue');
console.log(parent.colors);//'red','green',
var instance2 = new SubType();
console.log(instance2.colors);//'red','green','blue'
原型继承.PNG

组合继承:构造函数+原型继承

function SuperType(){
    this.property =true;
    this.colors = ['red','green'];
}
SuperType.prototype.getSuperValue = function(){
    return this.property;
}

var parent = new SuperType();
function SubType(arg){
    SuperType.call(this,arg);
    this.property = false;//子类重写父类属性
}

SubType.prototype = new SuperType(); 

SubType.prototype.getSubType = function(){
    return this.property;
}
var instance = new SubType();
console.log(instance.getSuperValue());//false
instance.colors.push('blue');
console.log(instance.colors);//'red','green','blue'
console.log(parent.colors);//'red','green',
var instance2 = new SubType();
console.log(instance2.colors);//'red','green'
组合继承.PNG

寄生继承:

 function createAnother(original){
  var clone = object(original);
  clone.sayHi = function(){
    console.log('hi');
  }
  return clone;
}

var person = {
  name:"sherry",
  friends:['lisa']
}
var p = createAnother(person);

最佳实践:寄生组合继承


function inheritPrototype(subType,superType){
  var prototype = object(superType.prototype);  
  prototype.contructor = subType;
  subType.prototype = prototype;
}

另一种实现方式:

 function extend(Child, Parent) {
    var F = function(){};
    F.prototype = Parent.prototype;
    Child.prototype = new F();
    Child.prototype.constructor = Child;
    Child.uber = Parent.prototype;
  }

参考:《Javascript高级教程》

上一篇 下一篇

猜你喜欢

热点阅读