Creo que configuré todo correctamente usando la función de llamada para pasar la variable x del padre b, pero sigo recibiendo el error que es "newB.getX no es una función". Soy un principiante, por favor dame algunos consejos y explicaciones, gracias.
const a = function(x) { this.x = x } a.prototype = { getX() { return this.x; } } const b = function(x, y) { a.call(this, x); this.y = y; } b.prototype = { getY() { return this.y; } } const newB = new b('x', 'y'); console.log('question 5:', newB.getX()); console.log('question 5:',newB.getY());Haciendo a.call(this, x); solo ejecuta a constructor de , que solo asigna una propiedad a la instancia. No cambia ninguno de los prototipos internos. La cadena prototipo de newB permanece:
instancia (tiene la propiedad x ) <- b.prototype (tiene la propiedad getY) <-Object.prototype
a.prototype no está en la cadena, por lo que getX no está visible en la instancia.
Supongo que podría iterar sobre todas las propiedades del prototipo y asignarlas a la instancia.
const a = function(x) { this.x = x } a.prototype = { getX() { return this.x; } } const b = function(x, y) { a.call(this, x); for (const [key, prop] of Object.entries(a.prototype)) { this[key] = prop; } this.y = y; } b.prototype = { getY() { return this.y; } } const newB = new b('x', 'y'); console.log('question 5:', newB.getX()); console.log('question 5:',newB.getY()); O hazlo en a constructor de a
const a = function(x) { this.x = x; this.getX = () => this.x; } const b = function(x, y) { a.call(this, x); this.y = y; } b.prototype = { getY() { return this.y; } } const newB = new b('x', 'y'); console.log('question 5:', newB.getX()); console.log('question 5:',newB.getY()); O use una class , que es probablemente el método moderno preferido de subclasificación (en lugar de funciones de extensión manual)
class a { getX = () => this.x; constructor(x) { this.x = x; } } class b extends a { getY = () => this.y; constructor(x, y) { super(x); this.y = y; } } const newB = new b('x', 'y'); console.log('question 5:', newB.getX()); console.log('question 5:',newB.getY());