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

98
Visualizações
Losing the value of this keyword when using it with instance level variables in a class in javascript

I have two classes one of them is the parent class and the other one is the child class and what I'm trying to achieve is to access the values of child classe's instance level variables by using this keyword in a field that is declared in the parent class. But when I try to do so it returns undefined. Can anyone please explain what might be going wrong here. Below I've pasted a code snippet for your reference. Thanks!

class Parent {
  someField = {
     someValue: 'Values are ::: '+ this.value1 + ' ' + this.value2,
     childType2: "Some gibberish"
   }

  initialize(childType1) {
     this.someField = this.someField[childType1];
  }
}

class Child extends Parent {
   value1 = "someValue 1"
   value2 = "someValue 2"
} 

const child = new Child();
child.initialize("someValue");
console.log(child.someField);

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

It's not that this is wrong, it's a matter of timing. Your code initializing someField runs as part of the Parent constructor, before your code initializing value1 and value2 runs (as part of the Child constructor). So you get undefined when reading them.

The way public fields work in JavaScript, the definition of the property defined by the field declaration becomes part of the constructor's code, exactly as though you had written it at the beginning of the constructor (just after any call to super) (but [effective] using Object.defineProperty, not just simple assignment; details). That is, your code is the effectively the same as this:

class Parent {
    constructor() {
        Object.defineProperty(this, "someField", {
            value: {
                someValue: 'Values are ::: '+ this.value1 + ' ' + this.value2,
                childType2: "Some gibberish"
            },
            writable: true,
            enumerable: true,
            configurable: true
        });
    }

    initialize(childType1) {
        this.someField = this.someField[childType1];
    }
}

class Child extends Parent {
    constructor() {
        super();
        Object.defineProperty(this, "value1", {
            value: "someValue 1",
            writable: true,
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(this, "value2", {
            value: "someValue 2",
            writable: true,
            enumerable: true,
            configurable: true
        });
    }
} 

const child = new Child();
child.initialize("someValue");
console.log(child.someField);

about 4 years ago · Juan Pablo Isaza Relatório
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