【问题标题】:Why my __proto__ reference shows wrong name in console?为什么我的 __proto__ 参考在控制台中显示错误的名称?
【发布时间】:2021-04-05 23:43:18
【问题描述】:
我的 proto 引用“mike”实例指向“Student”,但正如它的名称显示“Person”,我不知道为什么会这样。下面是我的代码和控制台截图:
const Person = function (firstName,birthYear) {
this.firstName = firstName;
this.birthYear = birthYear;
}
Person.prototype.calcAge = function () {
console.log(2037 - this.birthYear);
}
const Student = function (firstName, birthYear, course){
Person.call(this,firstName,birthYear);
this.course = course;
};
Student.prototype = Object.create(Person.prototype)
Student.prototype.constructor = Student;
Student.prototype.introduce = function () {
console.log(`My name is ${this.firstName} and ,I study ${this.course}`);
}
const mike = new Student('Mike',2020, 'Computer Science');
console.log(mike);
当我在控制台上查看时,它显示 Person:
【问题讨论】:
标签:
javascript
oop
object
prototype
prototypal-inheritance
【解决方案1】:
Student.prototype = Object.create(Person.prototype)
在这种情况下,您正在创建一个新对象并将其设为Student.prototype 的值。新对象Student 以Person.prototype 作为其原型。
【解决方案2】:
您在 Chrome 控制台中看到的第一件事是Student。那是您的 mike 对象的“类型”。
另一方面,mike 的 __proto__ 属性引用了创建此实例的原型。您的代码已使用以下语句明确定义了该原型:
Student.prototype = Object.create(Person.prototype);
所以,从那一刻起,Student.prototype instanceof Person 为真,但Student.prototype instanceof Student 为假。所有使用new Student 创建的实例都将在其__proto__ 属性中引用Student.prototype。所以你看到的和预期的一样。
进行以下分配的事实不会改变这种行为:
Student.prototype.constructor = Student;
这是一个表面上的更改,并不能确定 Student 创建的实例的性质。这可能会误导你。
类语法
您提供的代码执行设置原型链所需的步骤,其中Student 继承自Person。
在现代 JavaScript 中,实现这一点并不那么神秘。现在你可以这样写这个例子:
class Person {
constructor(firstName,birthYear) {
this.firstName = firstName;
this.birthYear = birthYear;
}
calcAge() {
console.log(2037 - this.birthYear);
}
}
class Student extends Person {
constructor(firstName, birthYear, course) {
super(birthYear, course);
this.course = course;
}
introduce() {
console.log(`My name is ${this.firstName} and ,I study ${this.course}`);
}
}
const mike = new Student('Mike',2020, 'Computer Science');
console.log(mike);
控制台中的结果也会在这里确认Student实例的原型对象是Person的实例(不是Student的实例)。