【发布时间】:2021-11-08 14:56:06
【问题描述】:
在下面的代码中,当我执行 console.log(teacher1.getDetails());属性值显示未定义,但是当我执行 console.log(teacher1.personName) 或 console.log(teacher.mainSubject) 时,它显示属性值。这里发生了什么?我错过了什么?有人可以解释一下吗?以及如何让它发挥作用?
let Person = function(personName, age) {
this.personName = personName;
this.age = age;
};
Person.prototype.getDetails = function() {
return `Person Name:${this.personName}. Age is ${this.age}.`;
};
//Child constructor function
let Teacher = function(personName, age, mainSubject) {
Person.call(this, personName, age);
this.mainSubject = mainSubject;
};
Teacher.prototype = Object.create(Person.prototype); //inheritance
Teacher.prototype.getDetails = function() {
return `${this.__proto__.getDetails()} Main subject is ${this.mainSubject}.`; //optionally invoke the parent method.
};
let teacher1 = new Teacher("Sakib", 35, "Physics");
console.log(teacher1.getDetails()); //invokes Teacher.getDetails() method (child's method).
【问题讨论】: