-
Notifications
You must be signed in to change notification settings - Fork 3
/
67 Getters and Setters.html
65 lines (59 loc) · 1.98 KB
/
67 Getters and Setters.html
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<!--
Classes also allows you to use getters and setters.
It can be smart to use getters and setters for your properties,
especially if you want to do something special with the value before returning them,
or before you set them.
To add getters and setters in the class, use the get and set keywords.
-->
<script>
//Create a getter and a setter for the "carname" property:
class car{
constructor(brand){
this.carName=brand;
}
get cName(){
return this.carName;
}
set cName(name){
this.carName=name;
}
}
const mycar=new car("BMW");
console.log(mycar.cName);
//Use a setter to change the carname to "Volvo":
mycar.cName="Volvo"
console.log(mycar.cName)
//Note: even if the getter is a method, you do not use parentheses when you want to get the property value.
//he name of the getter/setter method cannot be the same as the name of the property, in this case carName
//Example Two:
class myCycle{
constructor(name,type){
this.name=name;
this.type=type;
}
get checkCycle(){
return "Cycle Name is: "+this.name+", and its type is: "+this.type;
}
set cycleName(name){
this.name=name;
}
set cycleType(type){
this.type=type;
}
}
const cycle=new myCycle("Honda","Sports");
console.log("cycle info:",cycle.checkCycle)
cycle.cycleName="BMW"
cycle.cycleType="Mountain"
console.log("updated cycle info:",cycle.checkCycle)
</script>
</body>
</html>