【发布时间】:2017-02-05 13:41:06
【问题描述】:
我检查了以下问题: javascript what is property in hasOwnProperty? 和 javascript hasOwnProperty and prototype 但找不到我的问题的答案。这是我的代码: 但有些答案让我感到困惑(不像预期的那样)。
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属性?您期望它的价值是多少? -
如果我说“不符合预期”是在比较 console.log(Object.getOwnPropertyNames(new Student())); 的答案时// 上面写着 [ studentName, schoolName ] 和 console.log(Student.prototype.hasOwnProperty("studentName"));这对 studentName 来说是假的。有人可以解释这两种方法的行为,一种在对象上,另一种在原型上。为什么方法 printStudentName 是原型的属性,而 studentName 是对象的属性(或类似的东西)。谢谢。
标签: javascript properties prototypal-inheritance