我不能让我的原型在我的构造函数中做出反应
问题描述:
我有三个构造函数。学校,教师和学生。 到目前为止,我的代码中的所有内容都感觉很好,但我似乎无法在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();
答
在那些类构造函数继承原型,你需要给你打电话是继承什么样的构造,在当前对象的上下文。
例如在您的学生构造你需要做的这个
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的默认参数应该是什么?
+0
感谢您的帮助。我刚开始在课堂上开始面向对象的js,这是让老师改变学生课堂,对学生进行拘留等任务之一 – dutchkillsg
你是如何初始化学校的? – karthick