0

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())
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
  • 1
    Does this answer your question? [How does the "this" keyword work?](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) and https://stackoverflow.com/questions/4011793/this-is-undefined-in-javascript-class-methods – evolutionxbox May 04 '22 at 18:30
  • @SeanLawton FYI: W3Schools is well-known to be a poor learning resource. They often provide out of date, incomplete, or flat out incorrect information. A great resource for JavaScript and surrounding technologies is the [Mozilla Developers Network](https://developer.mozilla.org/). – Scott Marcus May 04 '22 at 18:35

1 Answers1

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());
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132