JS继承各模式优缺点

<!-- 原型链继承 -->
  <script>
    function Parent() {
      this.name = ['kevin','jane'] // 缺点1 Child实例会共享这个属性
    }
    Parent.prototype.getName = function () {
      console.log(this.name)
    }
    function Child() {}
    Child.prototype = new Parent() // 缺点2 若Parent接收参数,也只能在此处传递,不能做到在创建Child实例时传递
    Child.prototype.constructor = Child
    var child1 = new Child()
    console.log(child1.getName()) // kevin
  </script>
<!-- 借用构造函数继承 -->
  <script>
    function Parent(name){
      this.name = name
    }
    Parent.prototype.getName = function(){} // 缺点2 Child的实例无法访问父类原型上的方法,可以通过组合继承解决
    function Child(name,age){
      this.age = age
      Parent.call(this,name) // 缺点1 每创建一个Child实例,都会去调用Parent方法
    }
    var child = new Child('java',18)
  </script>
<!-- 组合继承 常用继承方法 -->
  <script>
    function Parent(name){
      this.name = name
      this.colors = ['red','green']
    }
    Parent.prototype.getName = function(){console.log(this.name)} 
    function Child(name,age){
      this.age = age
      Parent.call(this,name) 
    }
    Child.prototype = new Parent() // 小缺点1 Child.prototype上会存在colors属性,占用了内存,可以通过寄生组合继承解决
    Child.prototype.constructor = Child
    var child1 = new Child('java',18)
  </script>
<!-- 寄生组合继承 -->
  <script>
    function Parent(name){
      this.name = name
      this.colors = ['red','green']
    }
    Parent.prototype.getName = function(){console.log(this.name)} 
    function Child(name,age){
      this.age = age
      Parent.call(this,name) 
    }
    var Fn = function(){}
    Fn.prototype = Parent.prototype // 此处把prototype赋值给Fn不会浪费内存,因为prototype是引用类型
    Child.prototype = new Fn()
    Child.prototype.constructor = Child
    var child1 = new Child('java',18)
  </script>

来自JavaScript深入之继承的多种方式以及优缺点

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值