我有三个构造函数。学校,教师和学生。 到目前为止,我的代码中的所有内容都感觉还可以,但我似乎无法在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();
答案 0 :(得分:1)
在继承原型的类的构造函数中,您需要在当前对象的上下文中调用您继承的构造函数。
e.g。在你的学生构造函数中,你需要这样做
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
}
调用教师构造函数并初始化教师 继承 的所有成员变量。
与teacher
school
相同
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的默认参数应该是什么?