关于js种继承的六种实现方法以及其优缺点

//实现继承的几种方式
//第1种方式 使用call或者apply方法改变this指向
//缺点:虽然改变了this的指向但是Child构造函数并不会指向Parent的原型链
let Parent1 = function(){
  this.name = 'name'
}
Parent1.prototype.say=function(){console.log('say')}
let Child1 = function(){
  Parent1.call(this)
  this.type = 'child'
}
let c1 = new Child1()
//c1.say() TypeError: c1.say is not a function
//第2种方式 让Child的原型对象指向Parent实例
//缺点:因为Child的原型对象为Parent的实例,c2实例对象会直接修改Parent里面的属性
let Parent2 = function(){
  this.name = 'name'
  this.arr = [1,2,3]
}
let Child2 = function(){
  this.type = 'child'
}
Child2.prototype = new Parent2()
let c2 = new Child2()
let c3 = new Child2() 
c2.arr.push(4)
console.log(c2.arr,c3.arr)//Array(4) [1, 2, 3, 4]   Array(4) [1, 2, 3, 4]
//第3种方式 12混合使用
//缺点;重复实例化父级对象
let Parent3 = function(){
  this.name = 'name'
  this.arr = [1,2,3]
}
let Child3 = function(){
  Parent3.call(this)
  this.type = 'child'
}
Child3.prototype = new Parent3()
let c4 = new Child3()
let c5 = new Child3() 
c4.arr.push(4)
console.log(c4.arr,c5.arr)
//第4种方式 混合升级 因为Child3.prototype = new Parent3() 而实例Parent3继承的是他的原型对象上的方法
//所以可以像下面这样写
//缺点:无法找到正确的找到child的constructor
let Parent4 = function(){
  this.name = 'name'
  this.arr = [1,2,3]
}
let Child4 = function(){
  Parent4.call(this)
  this.type = 'child'
}
Child4.prototype = Parent4.prototype
let c6 = new Child4()
let c7 = new Child4()
console.log(c6.constructor) //输出为Parent4,实际上应该是Child4
//第5种方式 使用Obeject.create()方法
let Parent5 = function(){
  this.name = 'name'
  this.arr = [1,2,3]
}
let Child5 = function(){
  Parent5.call(this)
  this.type = 'child'
}
Child5.prototype = Object.create(Parent5.prototype)//此时的Child的原型链已经指向了Parent
Child5.prototype.constructor = Child5 //指明构造函数
let c8 = new Child5()
console.log(c8.constructor)//Child5
//第6种方式 使用Es6语法创建
class Parent6{
  constructor(name){
    this.name=name
  }
}
class Child6 extends Parent6{
  constructor(name){
    super(name)
    this.type ='child'
  }
}
let c9 = new Child6('hhh')
console.log(c9.name,c9.type)//hhh child

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值