我从Pluralsight课程中学习了Javascript中的原型。我对此有些困惑。
下面是一个例子。我有两个建设者--人和学生:
function Person(firstName, lastName, age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.getFullName = function() {
console.log(this.firstName + this.lastName)
}
}
function Student(firstName, lastName, age) {
this._enrolledCourses = [];
this.enroll = function (courseId) {
this._enrolledCourses.push(courseId);
};
this.getCourses = function () {
return this._enrolledCourses;
};
}然后创建一个学生实例:
let michael = new Student("Michael", "Nguyen", 22);现在,在本教程中,它说,为了让michael从Person继承所有东西,有两个步骤:
Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student;Student中的
Personfunction Student(firstName, lastName, age) {
Person.call(this, firstName, lastName, age); <---- this line
this._enrolledCourses = [];
this.enroll = function (courseId) {
this._enrolledCourses.push(courseId);
};
this.getCourses = function () {
f;
return this._enrolledCourses;
};
}但是,如果我移除步骤1,并且只跟随步骤2,结果将保持不变。michael仍然能够从Person继承所有东西。问题是,第一步到底有什么意义?如果我删除步骤2,并且只执行步骤1,michael将无法从Person继承任何东西。
这是课程网址:
发布于 2022-03-23 19:09:09
这是因为您的构造函数将所有属性添加到this中,而不是使用原型。
通常,方法被添加到原型中,而不是每个实例。
function Person(firstName, lastName, age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
Person.prototype.getFullName = function() {
console.log(this.firstName + this.lastName)
}如果不创建原型链,Student将不会继承以这种方式定义的方法。
https://stackoverflow.com/questions/71592717
复制相似问题