【问题标题】:How does the prototype object of an inherited class equal a new instance of the original class in JavaScript?继承类的原型对象如何等于 JavaScript 中原始类的新实例?
【发布时间】: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


【解决方案1】:

存在功能上的差异。您的方式将 Student 的原型分配为 Person 的 reference。任何一个原型的突变都会发生在两者中。相反,当您在示例中进行分配时,您将传递一个 new Object 和 Person 原型的(深层)副本。看看下面的截图。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-27
    • 1970-01-01
    相关资源
    最近更新 更多