1// ES6 get and set
2class Person {
3 constructor(name) {
4 this._name = name;
5 }
6
7 get name() {
8 return this._name.toUpperCase();
9 }
10
11 set name(newName) {
12 this._name = newName; // validation could be checked here such as only allowing non numerical values
13 }
14
15 walk() {
16 console.log(this._name + ' is walking.');
17 }
18}
19
20let bob = new Person('Bob');
21console.log(bob.name); // Outputs 'BOB'
1let obj = {
2 log: ['a', 'b', 'c'],
3 get latest() {
4 if (this.log.length === 0) {
5 return undefined;
6 }
7 return this.log[this.log.length - 1];
8 }
9};
10
11obj.log.push('d');
12console.log(obj.latest); //output: 'd'
1/*Getter functions are meant to simply return (get) the value of an object's
2private variable to the user without the user directly accessing the private
3variable.*/
4/*Setter functions are meant to modify (set) the value of an object's private
5variable based on the value passed into the setter function. This change could
6involve calculations, or even overwriting the previous value completely.*/
7class Book {
8 constructor(author) {
9 this._author = author;
10 }
11 // getter
12 get writer() {
13 return this._author;
14 }
15 // setter
16 set writer(updatedAuthor) {
17 this._author = updatedAuthor;
18 }
19}
20const novel = new Book('anonymous');
21console.log(novel.writer); // anonymous
22novel.writer = 'newAuthor';
23console.log(novel.writer); // newAuthor
1const language = {
2 set current(name) {
3 this.log.push(name);
4 },
5 log: []
6}
7
8language.current = 'EN';
9language.current = 'FA';
10
11console.log(language.log);
1var person={firstname:"chetha",secondname="kumar",get fullname()
2{
3 return this.firstname+" "+this.secondname;
4}
5document.write(person.fullname);
6var person={firstname:"chethan",secondname="kumar",course:"",set course(x)
7{
8 this.course=x;
9}
10person.course="bca";
11document.write(person.course);
11) Syntax reasons. It’s easier and faster to read code
2created with accessor functions
32) Encapsulation. I can create safer code with accessor functions.