Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

259
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda