He estado aprendiendo sobre prototipos en Javascript en un curso de Pluralsight. Y tengo cierta confusión al respecto.
Aquí está el ejemplo. Tengo 2 constructores Persona y Estudiante:
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; }; }Luego crea una instancia de Student:
let michael = new Student("Michael", "Nguyen", 22); Ahora, en el tutorial, dice que para que michael herede todo de Person , hay 2 pasos:
Student.prototype = Object.create(Person.prototype); Student.prototype.constructor = Student;Person dentro Student : function 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; }; } Sin embargo, si elimino el paso 1 y solo sigo con el paso 2, el resultado sigue siendo el mismo. michael todavía puede heredar todo de Person . La cosa es, ¿cuál es el punto del paso 1 de todos modos? Si elimino el paso 2 y solo me llevo bien con el paso 1, michael no podrá heredar nada de Person .
Para su información, aquí está la URL del curso: https://app.pluralsight.com/course-player?clipId=f1feb535-bbdd-4255-88e3-ed7079f81e4e
Esto se debe a que sus constructores están agregando todas las propiedades a this , no está usando los prototipos.
Normalmente, los métodos se agregan al prototipo, no a cada instancia, por ejemplo
function Person(firstName, lastName, age) { this.firstName = firstName; this.lastName = lastName; this.age = age; } Person.prototype.getFullName = function() { console.log(this.firstName + this.lastName) } Si no crea la cadena de prototipos, Student no heredará un método definido de esta manera.