-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGetters & Setters.js
More file actions
44 lines (34 loc) · 1.04 KB
/
Getters & Setters.js
File metadata and controls
44 lines (34 loc) · 1.04 KB
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
44
/*You can add methods prefixed with 'get' or 'set' to create a getter and setter, which are two different pieces
of code that are executed based on what you are doing: accessing the variable, or modifying its value.
Getters and setters are very useful when you want to execute some code upon changing the property value,
or if you want to create a “computed” property. You can alter the values you return by using a getter.
*/
class Person {
constructor(name) {
this._name = name
}
set name(value) {
this._name = value
}
get name() {
return this._name
}
}
//If you only have a getter, the property cannot be set, and any attempt at doing so will be ignored.
class Person {
constructor(name) {
this._name = name
}
get name() {
return this._name
}
}
//If you only have a setter, you can change the value but not access it from the outside.
class Person {
constructor(name) {
this._name = name
}
set name(value) {
this._name = value
}
}