Languages
[Edit]
EN

JavaScript - add getter to the existing object

0 points
Created by:
Zoya-Gaines
653

In this article, we would like to show you how to add getter to the existing object in JavaScript.

Quick solution:

// ONLINE-RUNNER:browser;

const user = {
  id: '1',
  username: 'Tom',
  role: 'admin',
};

// add getter
Object.defineProperty(user, 'isAdmin', {
  get: function () {
    return this.role == 'admin';
  },
});

console.log(user.isAdmin); // true

 

Practical example

In this example, we use Object.definePropery() to define the getter for the existing numbers object.

// ONLINE-RUNNER:browser;

const numbers = {
  name: 'prime numbers',
  values: [2, 3, 5, 7],
};

// add getter
Object.defineProperty(numbers, 'last', {
  get: function () {
    if (this.values.length > 0) {
      return this.values[this.values.length - 1];
    }
    return undefined;
  },
});

console.log(numbers.last);  // 7

Output:

7

Related posts

References

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join