繁体   English   中英

继承的 class 的原型 object 如何等于 Z686155AF75A60A0F6E9D80CE1 中原始 class 的新实例?

[英]How does the prototype object of an inherited class equal a new instance of the original class in JavaScript?

我一直在学习JavaScript中的inheritance,在https//www.tutorial-javascriptsteacher.com/

代码如下:

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();

据我了解,当创建 object 实例时,其__proto__属性指向该类的原型 object。

按照这个逻辑,代码不应该是:

Student.prototype = new Person().__proto__; ?

我真的很感激一些澄清!

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

问题的方法 示例的方法

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM