-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgetter-setter.js
30 lines (24 loc) · 1.01 KB
/
getter-setter.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// The get syntax binds an object property to a function that will be called when that property is looked up.
// this way we can use function like a property
// Getter is used to get object property dynamically and it is read only
// to make it write, we have to use setter, setter is used to assign some
// value to the property dynamically
// getter and setter are also used to modify the private member of the object
const person = {
firstName: "Aashish",
lastName: "Chapain",
// Getter
get fullName() {
return `${this.firstName} ${this.lastName}`;
},
// Setter
set fullName(value) {
const names = value.split(' ');
this.firstName = names[0];
this.lastName = names[1];
}
}
console.log(person.fullName); // Here we print Aashish Chapain using the getter
person.fullName = 'Viviane Sedola' // Here with the setter we modify the full name to Viviane Sedola
console.log(person.fullName) // Now with the getter the result is Viviane Sedola
console.log(person)