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

91
Views
Function called inside an variable returns undefined

I am trying to get output from an function, where on calling it it should return John temp (2021) but am getting John undefined (undefined)

const user = {
    username : 'John',
    type: 'temp',
    yearJoin: 2021,
    userString(){
        function getUserDetails (){
            return `${this.type} (${this.yearJoin})`
        }
        return `${this.username} ${getUserDetails()}`;
    }
}
console.log(user.userString())

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You need to set the scope of the getUserDetails call to this:

getUserDetails.call(this)

See:

const user = {
  username: 'John',
  type: 'temp',
  yearJoin: 2021,
  userString() {
    function getUserDetails() {
      return `${this.type} (${this.yearJoin})`
    }
    return `${this.username} ${getUserDetails.call(this)}`;
  }
}

console.log(user.userString());

You can clean this up, by moving the getUserDetails function up as a method on the object:

const user = {
  username: 'John',
  type: 'temp',
  yearJoin: 2021,
  getUserDetails() {
    return `${this.type} (${this.yearJoin})`
  },
  toString() {
    return `${this.username} ${this.getUserDetails()}`;
  }
}

console.log(user.toString());

Now take it one step further, as a class, and you have:

class User {
  constructor({ username, type, yearJoin }) {
    this.username = username;
    this.type = type;
    this.yearJoin = yearJoin;
  }
  getUserDetails() {
    return `${this.type} (${this.yearJoin})`
  }
  toString() {
    return `${this.username} ${this.getUserDetails()}`;
  }
}

const user = new User({
  username: 'John',
  type: 'temp',
  yearJoin: 2021
});

console.log(user.toString());

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!