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.

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.