Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

258
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!