四种继承模式详解

17 篇文章 0 订阅

目录

原型链继承:

借用构造函数:

共享原型:

圣杯模式:(继承模式集大成者,较完美解决方案)


本文介绍了继承模式逐步完善的过程,继承模式最终解决方案为--圣杯模式

原型链继承:

构造函数A通过new生成a对象,使得A.prototype指向对象b,而对象b由构造函数B生成,这样就形成了原型链的继承关系

单一,所以实例都会继承到父类实例的属性

a.__proto__ --> A.prototype === b b.__proto__ --> B.prototype

    Grand.prototype.lastName = 'Cheng';
    function Grand() {

    }

    var grand = new Grand();

    Father.prototype = grand;
    function Father() {
      this.name = 'ming';
    }

    var father = new Father();

    Son.prototype = father;
    function Son() {

    }

    var son = new Son();

    console.log(son.lastName);   // 'Cheng'
    console.log(son.name);     // 'ming'

 

借用构造函数:

通过call或者apply,在A的构造函数中执行调用B构造函数

执行了两次方法(缺点)

同原型链继承,过多的继承了无用的属性(缺点)

    function Person(name, age, sex) {
      this.name = name;
      this.age = age;
      this.sex = sex;
    }

    function Student (name, age, sex, grade) {
      Person.call(this, name, age, sex);
      this.grade = grade;
    }

    var student = new Student();

 

共享原型:

使得A.prototype = B.prototype

缺少个性化,如若想给A.prototype上面加自己的属性或方法,B.prototype也会加上

    Father.prototype.lastName = 'cheng';
    function Father() {

    }
    function son() {

    }
    // son.prototype = Father.prototype;
    function inherit(Target, Origin) {
      Target.prototype = Origin.prototype;
    }
    
    inherit(Son, Father);

    var son = new Son();
    console.log(son.lastName);  // 'cheng'

 

圣杯模式:(继承模式集大成者,较完美解决方案)

共享原型和原型链组合的方式

参数接收的分别是要继承的构造函数被继承的构造函数,之所以参数设定构造函数,是因为这样之后由改构造函数产生的对象都会被继承

    // 接着共享原型改造 inherit
    function inherit(Target, Origin) {
      function F() {};
      F.prototype = Origin.prototype;
      Target.prototype = new F(); 
    // 至此功能已经实现,下面是便利使用
      Target.prototype.constuctor = Target;     //由于继承了Origin,target的结构体变成了Origin的,所以要重新赋值
      Target.prototype.uber = Origin.prototype;   //设置uber  当想知道继承自谁时,直接调用即可
    }

    //雅虎精简版
    var inherit = (function() {
      var F = function() {};
      return function(Target, Origin) {
        F.prototype = Origin.prototype;
        Target.prototype = new F();
        Target.prototype.constuctor = Target;
        Target.prototype.uber = Origin.prototype;
      }
    }());

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值