继承类的原型对象如何等于JavaScript中原始类的新实例?

问题描述 投票:6回答:1

我一直在学习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__;

我非常感谢您作出澄清!

javascript inheritance prototype proto
1个回答
2
投票

存在功能上的差异。您的方式将Student的原型分配为Person的reference。两种原型都将发生突变。相反,当您按照示例进行分配时,您将传递new Object及其(深)Person原型的副本。请看以下屏幕截图。

Question's methodExample's method

© www.soinside.com 2019 - 2024. All rights reserved.