【发布时间】:2020-09-26 04:25:34
【问题描述】:
我一直在学习 JavaScript 中的继承,在 https://www.tutorialsteacher.com/javascript/inheritance-in-javascript 的教程中的一行代码看不懂。
代码如下:
function Person(firstName, lastName) {
this.FirstName = firstName || "unknown";
this.LastName = lastName || "unknown";
}
Person.prototype.getFullName = function () {
return this.FirstName + " " + this.LastName;
}
function Student(firstName, lastName, schoolName, grade)
{
Person.call(this, firstName, lastName);
this.SchoolName = schoolName || "unknown";
this.Grade = grade || 0;
}
//Student.prototype = Person.prototype;
Student.prototype = new Person();
Student.prototype.constructor = Student;
var std = new Student("James","Bond", "XYZ", 10);
alert(std.getFullName()); // James Bond
alert(std instanceof Student); // true
alert(std instanceof Person); // true
我不明白的部分是注释行之后的那一行,即:
Student.prototype = new Person();
据我了解,创建对象实例时,其__proto__ 属性指向类的原型对象。
按照这个逻辑,代码不应该是:
Student.prototype = new Person().__proto__;?
非常感谢您的澄清!
【问题讨论】:
-
它不应该这样写
Student.prototype = new Person().__proto__;,你可以但不鼓励以这种方式实现,而且根据MDN 还弃用了另一件事 proto检查这个SO question
标签: javascript inheritance prototype proto