EN
JavaScript - add getter to the existing object
0
points
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