How to Access Object Literal Properties in the Same Object?

Starting with ES5, you can add a getter to an object literal, in which you can access an object's own properties using the "this" keyword.

A getter method is defined using the get keyword followed by the function name, and can be accessed like other object properties.

For example:

// ES5+
const person = {
  firstName: 'john',
  lastName: 'doe',
  // ...
  get fullName() { return `${this.firstName} ${this.lastName}`; },
};

console.log(person.fullName); // 'john doe'

As you can see in the example above, in the fullName getter method, this.firstName and this.lastName refer to the firstName and lastName properties of the person object. This shows how you can create self-references in object literals using the "this" keyword.


Hope you found this post useful. It was published . Please show your love and support by sharing this post.