Overview
With getters and setters you can manipulate, and add methods to your class. While also making their properties more accessible
Code Samples
Getters
- Getters are usefull for controlling what we actually return from a class, for instance returning the value in uppercase
To use getters, and setters you use the get and set reserved keywords, and also add the _ symobol;
Creating a basic getter Example
//es6 Getters and Setters
//Getters are usefull for controlling what we actually return from a class, for instance returning the value in uppercase
class Person{
constructor(name) {
this._name = name;
}
//Defining a Getter
get name() {
return this._name;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Creating a basic setter Example
//es6 Getters and Setters
//Getters are usefull for controlling what we actually return from a class, for instance returning the value in uppercase
class Person{
constructor(name) {
this._name = name;
}
get name() {
return this._name;
}
set name(value) {
this._name = value;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
Example : returning the uppercase, and using setters to check if the value exists and setting it if true
//es6 Getters and Setters
//Getters are usefull for controlling what we actually return from a class, for instance returning the value in uppercase
class Person{
constructor(name) {
this._name = name;
}
get name() {
return this._name.toUpperCase();
}
set name(value) {
if(value.length > 2) {
this._name = value;
}
console.log('Names value didnt meet the requirements');
}
}
//Using our class
let person = new Person('Annabelle');
console.log(person)
//Setting the value for name with the required name paramater length
person.name = 'Violet'
//Setting the value for name without the required name paramater length
//person.name = 'A'
console.log(person)
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
31
32
33
34
35
36
37
38
39
40
41
42
43
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
31
32
33
34
35
36
37
38
39
40
41
42
43
Example : Using the getter
class Person{
constructor(name) {
this._name = name;
}
get name() {
return this._name.toUpperCase();
}
set name(value) {
if(value.length > 2) {
this._name = value;
}
console.log('Names value didnt meet the requirements');
}
}
//Using our class
let person = new Person('Annabelle');
//Setting the value for name with the required name paramater length
person.name = 'Violet'
//Using the getter to access the name value
console.log(person.name)
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
31
32
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
31
32