Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

103
Visualizações
Javascript arrow func in subclass cannot be found by super class

What I would like to achieve: Essentially, I would like my subclass to have a lexically-bound this function. However, I would like the super class to check that the subclass has an instantiation of this lexically-bound function.

This is how I would prefer to write the code, but it doesn't work:

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();

Yet this works:

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();

and this works:

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();

Could someone please explain why my first example is failing. It seems to me that bark() isn't in the prototype chain somehow but I'm not sure why.

about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda