我檢查了問題: javascript what is property in hasOwnProperty? 和 javascript hasOwnProperty and prototype 但無法找到答案我的問題。這裏是我的代碼: 但有些答案令我困惑(不像預期的那樣)。的JavaScript hasOwnProperty原型和繼承
function School(schoolName) {
this.schoolName = schoolName;
}
School.prototype.printSchoolName = function() {
console.log(this.schoolName);
}
function Student(studentName, schoolName) {
this.studentName = studentName;
this.schoolName = schoolName; // alternative : School.call(this, schoolName);
}
Student.prototype = new School(); // force l'héritage des propriétés de School
Student.prototype.printStudentName = function() {
console.log(this.studentName);
}
var s = new Student("Victor", "IUT");
s.printStudentName(); // works fine
s.printSchoolName(); // works fine
console.log(Student.prototype.hasOwnProperty("printStudentName")); // works as expected: true
console.log(Student.prototype.hasOwnProperty("printSchoolName")); // works as expected: false
console.log(Student.prototype.hasOwnProperty("studentName")); // NOT as expected: false
console.log(School.prototype.hasOwnProperty("schoolName")); // NOT as expected: false
console.log(Object.getOwnPropertyNames(new School())); // schoolName
console.log(Object.getOwnPropertyNames(new Student())); // studentName, schoolName
最後2個警報不提的方法,但這些方法已經被hasOwnProperty檢測。令人費解。謝謝。
說**你期望什麼**,你看到了什麼,以及爲什麼這不是你的期望。 –
順便說一下,我的失敗答案我也看到你的繼承是不現實的......學生繼承學校? –
你爲什麼期望'Student.prototype'擁有自己的'studentName'屬性?你期望它的價值是什麼? – Bergi