zoukankan      html  css  js  c++  java
  • Javascript 对象(二) 基于原型的继承

    1. 继承中最重要的两个地方:设置原型和构造函数的引用

      将”子类“原型指向父类的原型

      Teacher.prototype = Object.create(Person.prototype);
      

      将”子类“原型上的 constructor 属性指向子类构造函数

      Teacher.prototype.constructor = Teacher;
      
    2. 分析

      定义 Person 和 Teacher 两个函数,不进行关联

      // 定义 Person
      function Person(first, last, age, gender, interests) {
        this.name = {
          first,
          last,
        };
        this.age = age;
        this.gender = gender;
        this.interests = interests;
      }
      
      Person.prototype.greeting = function () {
        console.log('HI, I am ' + this.name.first);
      };
      
      let person1 = new Person('peter', 'jackson', 49, 'male', ['movie', 'footable']);
      person1.greeting(); // HI, I am peter
      
      // 定义 Teacher
      function Teacher(first, last, age, gender, interests, subject) {
        // 调用 Person 的构造方法进行初始化
        Person.call(this, first, last, age, gender, interests);
        this.subject = subject;
      }
      

      创建一个 Teacher 的实例

      let teacher1 = new Teacher('jack', 'sparrow', 28, 'male', ['music'], 'math');
      teacher1.greeting(); // Uncaught TypeError: teacher1.greeting is not a function
      

      由于 Teacher 没有定义 greeting 方法,原型上也没有,所以报错了。

      开始将 Teacher 的原型指向 Person 的原型

      Teacher.prototype = Object.create(Person.prototype);
      let teacher1 = new Teacher('jack', 'sparrow', 28, 'male', ['music'], 'math');
      teacher1.greeting(); // HI, I am jack
      

      打印以下几个属性

      console.log(Person.prototype);
      console.log(Teacher.prototype);
      console.log(Teacher.prototype.constructor);
      console.log(Teacher.prototype.__proto__ === Person.prototype); // true
      

      在 Chrome 中打印 Teacher.prototype,控制台显示 Person{},火狐就没有这样显示:

      可以发现,Teacher 的原型中并没有 constructor 属性,然而打印的话显示的是 Person() 函数。

      同时,Teacher 原型的原型已经指向了 Person 的原型。

      接下来,修改 Teacher 原型的 constructor 属性,令其指向 Teacher()

      Teacher.prototype.constructor = Teacher;
      

      这样,就完成了 Teacher 对 Person 的继承:Teacher 原型的 constructor 指向 Teacher(),这个原型的原型指向 Person 的原型。

    参考:

  • 相关阅读:
    【LOJ#6277】数列分块1
    【LOJ6284】数列分块8
    【洛谷P3275】糖果
    【洛谷P3810】陌上花开
    【洛谷P1052】过河 离散化+dp
    【洛谷P2042】维护数列
    【模板】文艺平衡树
    【洛谷P4145】花神游历各国
    【洛谷P4878】布局
    hdu 5748(LIS)
  • 原文地址:https://www.cnblogs.com/ainsliaea/p/13246717.html
Copyright © 2011-2022 走看看