Joo*_*n K 6 javascript inheritance prototype proto
我一直在学习 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
Run Code Online (Sandbox Code Playgroud)
我不明白的部分是注释行之后的行,即:
Student.prototype = new Person();
Run Code Online (Sandbox Code Playgroud)
据我了解,创建对象实例时,其__proto__属性指向类的原型对象。
按照这个逻辑,代码不应该是:
Student.prototype = new Person().__proto__; ?
我真的很感激一些澄清!
小智 2
存在功能上的差异。您的方式将 Student 的原型指定为对 Person 的原型的引用。任一原型的突变都会在两者中发生。相反,当您像示例中那样进行分配时,您将传递new Object带有 Person 原型的(深层)副本的 a 。看看下面的屏幕截图。
| 归档时间: |
|
| 查看次数: |
51 次 |
| 最近记录: |