Before go the Getters and Setters, you must learn about JS Objects.
Getters and Setters allow you to define Object Accessors.
In JavaScript, Accessor properties are methods that get or set the value of an object.
get - to define a getter method to get the property value.
set - to define a setter method to set the property value.
let person ={
firstName:"Title", // Data Properties
lastName: "Card",
/* fullName: () => {
return `${person.firstName} ${person.lastName}`;
}*/
fullName(){ // ES6 Features
return `${person.firstName} ${person.lastName}`; // Template literals
}
};
console.log(person.fullName());
//console.log(person.firstName + ' ' + person.lastName);
Getters is used to get the data(Keyword-get)
Setters is used to set the data(Keyword-set)
let person ={
firstName:"Title", // Data Properties
lastName: "Card",
/* fullName: () => {
return `${person.firstName} ${person.lastName}`;
}*/
// Getters is used to get the data
get fullName(){
return `${person.firstName} ${person.lastName}`;
},
// Setters is used to set the data
set fullName(value){
let values = value.split(" ");
//console.log(values)
this.firstName = values[0];
this.lastName = values[1];
// If the name is single word (only firstName)
//this.lastName = values[1] ?? "";
}
};
person.fullName = "Name Tag"
console.log(person.fullName);
Why Using Getters and Setters?
- It gives simpler syntax
- It allows equal syntax for properties and methods
- It can secure better data quality
- It is useful for doing things behind-the-scenes
Top comments (0)