gpt4 book ai didi

javascript - 我无法让我的构造函数中的原型(prototype)具有响应性

转载 作者:行者123 更新时间:2023-11-30 21:20:46 25 4
gpt4 key购买 nike

我有三个构造函数。学校、教师和学生。到目前为止,我的代码中的一切都感觉不错,但我似乎无法在 teacher.prototype 中获得两个函数来响应。我是 Js 的新手,正在尝试了解为什么这没有响应

//create a constructor for a school that has all teachers and students
function school(principal,teacher,student,classroom,detention){
this.principal = principal,
this.teacher = teacher,
this.student = student;
this.classroom = [],
this.detention = []
}
//create a constructor for teachers and students
//link them all together
function teacher(admin,name){
this.admin = admin
this.name = name
admin = true
//inherit some of the properties of school

}
function student(fname,lname,year,average){
this.fname = fname,
this.lname = lname,
this.year = year,
this.average = average
}
teacher.prototype = Object.create(school.prototype);
//teacher can send students to class
teacher.prototype.learn = function(student){
this.classroom.unshift(student)
}
//be able to move students to detention
teacher.prototype.punish = function(student){
this.detention.unshift(student)
}


student.prototype = Object.create(teacher.prototype)
student.prototype.fullDetails = function(){
return this.fname + ' ' + this.lname + " is in " + this.year + 'th' + ' grade and his average is ' + this.average;
}


var mr_feeney = new teacher(true,"Mr.Feeney")
var corey = new student("corey","mathews",10,88)
var shaun = new student("shaun","hunter",10,43)
var top = new student("topanga","lawrence",10,43)

shaun.learn();

最佳答案

继承原型(prototype)的类的构造函数中,您需要在当前对象的上下文中调用所继承对象的构造函数。

例如在你的学生构造函数中你需要这样做

function student(fname,lname,year,average){
//initialize all the member variables on this object that are created in the teacher constructor by calling teacher.call(this)
teacher.call(this);

this.fname = fname,
this.lname = lname,
this.year = year,
this.average = average
}

它调用教师构造函数并初始化所有从教师那里继承的成员变量。

这与继承自schoolteacher相同

function teacher(admin,name){
school.call(this);
this.admin = admin
this.name = name
admin = true
}

teacher.prototype = Object.create(school.prototype);

此外,请遵守约定,使用大写字母作为类名

function student()

应该是

function Student()

综上所述,您还有其他一些奇怪的架构 - 学生真的应该继承与老师相同的所有方法吗?老师真的应该继承与学校相同的所有属性/方法吗?从学生构造函数调用教师构造函数时,admin 和 name 的默认参数应该是什么?

关于javascript - 我无法让我的构造函数中的原型(prototype)具有响应性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45203018/

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