What are the set and get property in class of JS?

0 votes
31 views
Ravi Vishwakarma asked 11 days ago in Web Application by Ravi Vishwakarma

What are the set and get property in class of JS?

1 Answer

1 votes
Ethan Karla answered 9 days ago by Ethan Karla
Getters and setters allow you to define Object Accessors (Computed Properties).
Accessor Property. In JavaScript, accessor properties are methods that get or set the value of an object.
For that, we use these two keywords:
get - to define a getter method to get the property value
set - to define a setter method to set the property value
JavaScript Getter
In JavaScript, getter methods are used to access the properties of an object. For example,
const student = {

    firstName: 'Ravi vishwakarma',
    // accessor property(getter)
    get getName() {
        return this.firstName;
    }
};
console.log(student.firstName); // Ravi vishwakarma
console.log(student.getName); // Ravi vishwakarma
console.log(student.getName()); // error
In the above program, a getter method getName() is created to access the property of an object.
JavaScript Setter
In JavaScript, setter methods are used to change the values of an object. For example,
const student = {

    firstName: 'Ravi vishwakarma',
    //accessor property(setter)
    set changeName(newName) {
        this.firstName = newName;
    }
};
console.log(student.firstName); // Ravi vishwakarma
// change(set) object property using a setter
student.changeName = 'Water fall';
console.log(student.firstName); // Water fall
JavaScript Object.defineProperty()
In JavaScript, you can also use Object.defineProperty() method to add getters and setters. For example,
const student = {

    firstName: 'Ravi vishwakarma'
}
// getting property
Object.defineProperty(student, 'getName', {
    get : function () {
        return this.firstName;
    }
});
// setting property
Object.defineProperty(student, 'changeName', {
    set : function (value) {
        this.firstName = value;
    }
});
console.log(student.firstName); // Ravi vishwakarma
// changing the property value
student.changeName = 'Water fall';
console.log(student.firstName); // Water fall
In the above example, Object.defineProperty() is used to access and change the property of an object.
The syntax for using Object.defineProperty() is:
Object.defineProperty(obj, prop, descriptor)
The Object.defineProperty() method takes three arguments.
The first argument is the objectName.
The second argument is the name of the property.
The third argument is an object that describes the property.