// 1) In JavaScript, getter methods are used to access the properties of an object.
// we use get keyword to define a getter method to get or access the property value
const student = {
// data property
firstName: 'Chetan',
// accessor property(getter)
get getName() {
return this.firstName;
}
};
// accessing data property
console.log(student.firstName); // Chetan
// accessing getter methods or accessing the value as a property
console.log(student.getName); // Chetan
// trying to access as a method
console.log(student.getName()); // error
// In the above program, a getter method getName() is created to access the property of an object.
// Note: To create a getter method, the get keyword is used.
// 2) In JavaScript, setter methods are used to change the values of an object.
// we use set keyword to define a setter method to set the property value
const student = {
firstName: 'Chetan',
//accessor property(setter)
set changeName(newName) {
this.firstName = newName;
}
};
console.log(student.firstName); // Chetan
// change(set) object property using a setter
student.changeName = 'Jeny';
console.log(student.firstName); // Jeny
// In the above example, the setter method is used to change the value of an object.
// Note: To create a setter method, the set keyword is used.
public class Computer
{
int ram;
public int RAM
{
get
{
return ram;
}
set
{
ram = value; // value is a reserved word and it is a variable that holds the input that is given to ram ( like in the example below )
}
}
}