es5的继承实现

588 阅读1分钟

es6里可以直接用class实现继承,奈何es5没有,只能用其他方法实现继承了.

原型链实现

function Super(){
  this.num=[1,2,3]
}
Super.prototype.show=function(){
  console.log('show')
}
function Child(){}

Child.prototype=new Super();
var c1=new Child();

原型链继承的实现是如上,最重要的是重写原型对象Child.prototype=new Super();

缺点

原型上的引用类型一旦被重写,其他对象就都被重写了

c1.num[0]=13
console.log(c1)  //13
var c2=new Child();
console.log(c2)  //13

构造函数实现


function Super(){
  this.name='ss1'
}

function Child(){
  this.age=1;
  Super.call(this)
}
var a=new Child();
console.log(a.name)  //ss1

组合继承

通过构造函数和原型链的组合,进行继承的一种方式

function Super(){
  this.name='ss1'
}

Super.prototype.getName=function () {
  console.log('my name is ???')
}

function Child(){
  this.age=1;
  //继承属性
  Super.call(this)
}
//继承方法
Child.prototype=new Super();
var a=new Child();
console.log(a.name)  //ss1
a.getName();   //my name is ???

还有其他的两种,有时间再写把~~~