使用object.create和call的Javascript原型继承给出了非函数错误

时间:2017-11-15 19:32:38

标签: javascript inheritance

我正在围绕JavaScript原型继承。我正在接受以下链接的帮助:https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Inheritance

我有一个人物:

function Person(first, last, age, gender, interests) {
  this.name = {
    first,
    last
  };
  this.age = age;
  this.gender = gender;
  this.interests = interests;
};

我已将其继承到教师对象:

function Teacher(first, last, age, gender, interests, subject) {
  Person.call(this, first, last, age, gender, interests);

  this.subject = subject;
}

现在,我在Person原型上定义了一个函数:

Person.prototype.sayHello = function (){
   console.log("hello");
}

现在,我想通过老师打电话:

var teacher = new Teacher("khan","khan",1,"mile","hockey","english");
teacher.prototype.sayHello();

它给出了:

  

未捕获的TypeError:无法读取未定义的属性'sayHello'       at:1:19

直接调用它会产生相同的结果:

teacher.sayHello();

让我构建正确的构造:

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

teacher.sayHello();
  

VM203:1未捕获的TypeError:teacher.sayHello不是函数           at:1:9

结果相同。我错过了什么?

1 个答案:

答案 0 :(得分:2)

您只是调用Person函数并向其传递使用该函数初始化属性的上下文。如果你在其中调用另一个函数,就像调用它一样。 Person不在Teacher的原型链中。您还需要将其明确添加到链中。



function Person(first, last, age, gender, interests) {
  this.name = {
    first,
    last
  };
  this.age = age;
  this.gender = gender;
  this.interests = interests;
};

function Teacher(first, last, age, gender, interests, subject) {
  Person.call(this, first, last, age, gender, interests);

  this.subject = subject;
}

// Set the prototype an empty object which prototype is the Person.prototype
Teacher.prototype = Object.create(Person.prototype);
// Preserve the constructor
Teacher.constructor = Teacher;

Person.prototype.sayHello = function (){
   console.log("hello");
}

var teacher = new Teacher("khan","khan",1,"mile","hockey","english");
teacher.sayHello();