JavaScript深入之继承

JavaScript深入之继承

1.借助原型链实现继承

 function Parent(){
        this.name = "zhu"
      };
 Parent.prototype.getName = function(){
         console.log(this.name);
      };
 function Child() {

 };
 Child.prototype = new Parent();
 var child1 = new Child();
 child1.getName();//zhu

不过原型链继承有两个缺点:
1.引用实例会被所有实例共享

function Parent() {
        this.name = ["猪","狗"];
      }
      Parent.prototype.getName = function () {
        console.log(this.name);
      };
      function Child() {}
      Child.prototype = new Parent();
      var child1 = new Child();
      var child2 = new Child();
      child1.name.push("鸟")
      child1.getName();//['猪', '狗', '鸟']
      child2.getName();//['猪', '狗', '鸟']

我们向child1中push"鸟",但是child2中也会共享这个属性。
2.在创建 Child 的实例时,不能向Parent传参

2.构造函数继承

function Parent() {
        this.name = ["猪","狗"];
      }
      function Child() {
        Parent.call(this)
      }
      var child1 = new Child();
      child1.name.push("鸟")
      var child2 = new Child();
      console.log(child1.name);//['猪', '狗', '鸟']
      console.log(child2.name);//['猪', '狗']

这个避免了引用类型的属性被所有实例共享,而且child可以向Parent传参。

function Parent(name) {
        this.name = name;
      }
      function Child(name) {
        Parent.call(this, name);
      }
      var child1 = new Child("猪");
      console.log(child1.name); //猪
      var child2 = new Child("鸟")
      console.log(child2.name);//鸟

4.组合继承

Object.create ()是es5的方法,将传入的对象作为创建的对象的原型,下面是他的模拟实现。

function createObj(obj) {
    function F(){}
    F.prototype = obj;
    return new F();
}

我们将前两种组合并使用

 function Parent() {
        this.name = "parent";
        this.number = [1, 2, 3];
      }
      function Child() {
        Parent.call(this);
        this.type = "child";
      }
      Child.prototype = Object.create(Parent.prototype);
      Child.prototype.constructor = Child;
      var child1 = new Child();
      var child2 = new Child();
      child1.number.push(4)
      console.log(child1);
      console.log(child2);

控制台输出一下:
在这里插入图片描述

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值