2017-07-20 54 views
1

我有三個構造函數。學校,教師和學生。 到目前爲止,我的代碼中的所有內容都感覺很好,但我似乎無法在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(); 
+1

你是如何初始化學校的? – karthick

回答

1

在那些類構造函數繼承原型,你需要給你打電話是繼承什麼樣的構造,在當前對象的上下文。

例如在您的學生構造你需要做的這個

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 
} 

這就要求老師構造並初始化所有被繼承從老師的成員變量。

這是teacherschool

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

相關問題