Home > front end >  Retrieve values from properties of object within a function of that object
Retrieve values from properties of object within a function of that object

Time:10-03

My understanding is that, since they're in same block, the output should be "The full name of the user is John Doe". Yet I get undefined. Why is this happening?

let user = {
  firstname: 'John',
  lastname: 'Doe',
  getFullName: function() {
    return function() {
      console.log(`The full name of the user is ${this.firstname} ${this.lastname} `);
    }
  }
}
user.getFullName()();

CodePudding user response:

Your code snippet has a function, which creates another function, which accesses the this reference. This means that you actually create another inner block referencing a different this than the user you're actually targeting. The closest equivalent to your code would be as follows:

let user = {
  firstname: 'John',
  lastname: 'Doe',
  getFullName: function() {
      console.log(`The full name of the user is ${this.firstname} ${this.lastname} `);
  }
}
user.getFullName();

CodePudding user response:

The issue is because you're referencing this within the anonymous function you create to return from the getFullName() invocation. This is in a different scope to the outer user object, so the properties you attempt to access are not found.

To fix the problem you could refer to the user object explicitly in your template literal which builds the string output:

let user = {
  firstname: 'John',
  lastname: 'Doe',
  getFullName: function() {
    return function() {
      console.log(`The full name of the user is ${user.firstname} ${user.lastname} `);
    }
  }
}
user.getFullName()();

Or alternatively you could remove the anonymous function and build the string directly from getFullName(), like this:

let user = {
  firstname: 'John',
  lastname: 'Doe',
  getFullName: function() {
    console.log(`The full name of the user is ${this.firstname} ${this.lastname} `);
  }
}
user.getFullName();

Note the second set of parentheses are no longer required for the getFullName() invocation in the second method as you're returning a string, not a function.

CodePudding user response:

ES6 allow a simplified writing for objects functions:

let user =
  { firstname : 'John'
  , lastname  : 'Doe'
  , getFullName() 
    {
    console.log(`The full name of the user is ${this.firstname} ${this.lastname} `);
    } 
  }
user.getFullName();

You can also use a getter:

let user =
  { firstname : 'John'
  , lastname  : 'Doe'
  , get FullName() 
    {
    return `${this.firstname} ${this.lastname}`;
    } 
  }

console.log(`The full name of the user is ${user.FullName}`);

  • Related