0

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.

  • Hi, could you please share how you are calling `fullName`? Additionally, I encourage you to take a look at [this explanation](https://www.w3schools.com/js/js_object_properties.asp) – Lluís Muñoz Dec 31 '21 at 14:14
  • `this` is not the object `john` whereas inside the calcBMI function it is – charlietfl Dec 31 '21 at 14:16

1 Answers1

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}`;
}
fgb
  • 18,439
  • 2
  • 38
  • 52