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

224
Visualizações
Parent class constructor can't access child fields without Timeout

I am making an application using JavaScript. One thing that I noticed is that when I call super() from child class constructor, I cannot use child class fields.

For example:

class Parent {
    constructor() {
        console.log(this.x);
    }
}
class Child extends Parent {
    x = 5;
    constructor() {
        super();
    }
}
Output: undefined

As you see, the parent constructor cannot access the x field of the child constructor. There are similar questions on stackoverflow like:

Access JavaScript class property in parent class

The solution they give is to use an init() method on the Parent class. I realized that every method other than the constructor of the Parent class has access to child fields.

class Parent {
    init() {
        console.log(this.x);
    }
}
class Child extends Parent {
    x = 5;
    constructor() {
        super();
        this.init();
    }
}
Output: 5

However, I can also get access to the x field by using Timeout with delay of 0:

class Parent {
    constructor() {
        setTimout(() => console.log(this.x), 0);
    }
}
class Child extends Parent {
    x = 5;
    constructor() {
        super();
    }
}
Output: 5

All the answers on stackoverflow give the solution, but nobody explains how and why this happens. So my question is:

1. Why the constructor doesn't have access to fields of the child class?

2. Why adding a timeout function gives access to the fields of the child class?

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