es5的继承实现

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 ???
复制代码

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

转载于:https://juejin.im/post/5c7d1e65e51d4541af3016a9

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值