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 的原型。

参考:

原文地址:https://www.cnblogs.com/ainsliaea/p/13246717.html