How to add getter to an existing JavaScript Object

featured Image

In this article, we will learn how to add getter to an existing JavaScript Object.

In JavaScript, we can add a getter to an object using the get syntax.

The get syntax, let us to bind a Javasrcipt property to a function that can be called as any object property.

Syntax:

{get prop() { /* ... */ } }

Now let see an example

const student = {
    firstName: 'John',
    lastName: 'Adams',
    get fullName() {
        return this.firstName + ' ' + this.lastName;
    }
};

console.log(student.firstName)
console.log(student.fullName) //calling the getter method

Output:

John
John Adams

In the above code, we have created the getter method fullName() using the get keyword. And to get the value, we can access it as any javascript property using student.fullName .

From the above example, we know how to create a getter method and access the value of the property.

Now, let’s see how we can add a getter method to an existing JavaScript object.

Add getter method to existing object in Javascript

To add an getter to an existing object we have to use the Object.defineproperty method.

The Object.defineProperty()is a static method that defines a new property directly to an object, it can also modify an existing property on an object.

Syntax:

Object.defineProperty(obj, prop, descriptor)

obj the object on which we add the getter method.

prop – the name or property to be defined

descriptor – the descriptor for the property.

Let’s take the above example and add the fullName after the student object is already created.

const student = {
    firstName: 'John',
    lastName: 'Adams',
};

Object.defineProperty(student, 'fullName', {
  get: function() { return this.firstName + ' ' + this.lastName }
});

console.log(student.fullName)

Output:

John Adams

Related Posts

featured Image

Get the 10 characters from a string using JavaScript.

Here, in this article we will learn how to get the first 10 character from any string using JavaScript. Here we will be using JavaScript’s String method substring. What is…

Read more
featured Image

Convert date to long date format using JavaScript

In this article we will look into how to convert a date to a long date format using JavaScript. To convert it to a long format we will be using…

Read more
featured Image

Prevent body from scrolling when a modal is opened

Here, in this article, we will learn how to prevent the body from scrolling when a modal or a pop-up is opened using JavaScript. The scroll event is not cancelable….

Read more