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

257
Visualizações
After using the this keyword, why doesn't JavaScript realise that I've specified a property when I have?

I have an object which looks like this:

let john = {
    firstName: 'John',
    lastName: 'Smith',

    fullname: `${this.firstName} ${this.lastName}`,

    height: 1.95,
    mass: 92,

    calcBMI: function () {
        this.BMI = this.mass / this.height ** 2;
        return this.BMI
    }
}

Whenever I look at the fullName property, it just returns undefined. But when I type it out manually in the object (i.e fullName: 'John Smith'), I get the expected result: John Smith.

I looked through MDN web docs, but only found a few sentences on how an expression such as this.myProperty could return undefined if strict mode was activated, which it was in my case. But even when it was deactivated, the same problem occured.

Could anyone help me out?

P.S: I'm no professional coder, so it could just be me being a fool.

Edit: How I called fullName and one more doubt about my object

I 'm logging the fullName property to the console, if you were wondering.

One more thing - You may have noticed the calcBMI function in the object and that it also uses the this keyword. I'm wondering why it's working in there but not outside.

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

0

this is scoped to the currently executing function call. If it's used in the value of an object literal, it'll have the same value as it does outside the literal. It doesn't refer to the current object being defined.

To use this in fullname you could make it into a function instead:

fullname: function() {
    return `${this.firstName} ${this.lastName}`;
}
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