Lo que me gustaría lograr: Esencialmente, me gustaría que mi subclase tuviera una función this ligada léxicamente. Sin embargo, me gustaría que la superclase verifique que la subclase tenga una instanciación de esta función ligada al léxico.
Así es como preferiría escribir el código, pero no funciona:
class Animal { constructor(type) { this.animalType = type; if (!(this.bark instanceof Function)) { throw new Error('Found no bark'); } } } class Dog extends Animal { bark = () => { console.log('woof'); } } let max = new Dog('dog') max.bark();Sin embargo, esto funciona:
class Animal { constructor(type) { this.animalType = type; if (!(this.bark instanceof Function)) { throw new Error('Found no bark'); } } } class Dog extends Animal {} Dog.prototype.bark = () => { console.log('woof'); } let max = new Dog('dog') max.bark();y esto funciona:
class Animal { constructor(type) { this.animalType = type; if (!(this.bark instanceof Function)) { throw new Error('Found no bark'); } } bark = () => { console.log('woof'); } } class Dog extends Animal {} let max = new Dog('dog') max.bark();¿Podría alguien explicar por qué mi primer ejemplo está fallando? Me parece que bark() no está en la cadena de prototipos de alguna manera, pero no estoy seguro de por qué.