zoukankan      html  css  js  c++  java
  • 继承

    分为属性和方法的继承

    组合继承:原型链继承+构造函数继承

      使用原型链实现对原型属性和方法的继承,而通过借用构造函数来实现对实例属性的继承。这样,即通过在原型上定义方法实现了函数复用,又保证了每个实例都有它自己的属性。

    1
    2
    3
    4
    5
    6
    7
    function Parent(age){
      this.name = ['mike','jack','smith'];
      this.age = age;
    }
    Parent.prototype.run = function () {
      return this.name + ' are both' this.age;
    };

    function Child(age){

      Parent.call(this,age);

    }

    Child.prototype = new Parent();

    缺点:调用2次父类的构造函数

      

    原型式继承

      借助原型并基于已有的对象创建新对象,同时还不用创建自定义类型。

    1
    2
    3
    4
    5
    function obj(o){
      function F(){}
      F.prototype = o;
      return new F();
    }

      

    寄生式继承

      把原型式+工厂模式结合起来,目的是为了封装创建的过程

    1
    2
    3
    4
    5
    6
    7
    8
    9
    <script>
      function create(o){
        var f= obj(o);
        f.run = function () {
          return this.arr;//同样,会共享引用
        };
      return f;
      }
    </script>

      

    寄生组合继承

      通过借用构造函数来继承属性,通过原型链的混成方式来继承方法。

      基本思路:不必为了指定子类的原型而调用超类型的构造函数。本质上,使用寄生式继承来继承超类型的原型,然后再将结果指定给子类型的原型。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    function object(o) {
        function F() {}
        F.prototype = o;
        return new F();
    }
     
    function inheritPrototype(subType, superType) {
        var prototype = object(superType.prototype);  //创建对象
        prototype.constructor = subType;              //增强对象
        subType.prototype = prototype;                //指定对象
    }

      

  • 相关阅读:
    用KNN算法分类CIFAR-10图片数据
    特征处理(Feature Processing)
    实际问题中如何使用机器学习模型
    CS229 6.18 CNN 的反向传导算法
    【Leetcode】【Medium】Single Number II
    【Leetcode】【Medium】Single Number
    【Leetcode】【Easy】Merge Two Sorted Lists
    【Leetcode】【Easy】Valid Sudoku
    【Leetcode】【Easy】Implement strStr()
    【Leetcode】【Easy】Roman to Integer
  • 原文地址:https://www.cnblogs.com/xfcao/p/9999114.html
Copyright © 2011-2022 走看看