gpt4 book ai didi

Javascript 原型(prototype)继承与 object.create 和 call 没有给出函数错误

转载 作者:行者123 更新时间:2023-12-01 02:44:49 25 4
gpt4 key购买 nike

我正在研究 JavaScript 原型(prototype)继承。我正在使用以下链接的帮助: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 原型(prototype)上定义了一个函数:

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

现在,我想通过老师调用它:

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

它给出:

Uncaught TypeError: Cannot read property 'sayHello' of undefined at :1:19

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

teacher.sayHello();

让我正确设置构造函数:

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

teacher.sayHello();

VM203:1 Uncaught TypeError: teacher.sayHello is not a function at :1:9

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

最佳答案

您只需调用 Person 函数并将使用该上下文来初始化属性的上下文传递给他。您可以像调用其中的另一个函数一样调用它。 Person 不在 Teacher 的原型(prototype)链中。您还需要将其显式添加到链中。

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();

关于Javascript 原型(prototype)继承与 object.create 和 call 没有给出函数错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47315795/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com