-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclassesConstructor.js
More file actions
59 lines (46 loc) · 1.29 KB
/
classesConstructor.js
File metadata and controls
59 lines (46 loc) · 1.29 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
45
46
47
48
49
50
51
52
53
54
55
56
57
/*
** Overriding constructor
** According to specifications if a class inherits another class and it has no constructor of it's own
** It inherits the parent's constructor and initiates it with all the parameters
** In our case rabbit inherits Animal constructor
*/
class Animal {
constructor(name) {
this.speed = 0;
this.name = name;
}
run(speed){
this.speed = speed;
alert(`${this.name} runs with speed ${this.speed}`);
}
stop(){
this.speed = 0;
alert(`${this.name} stands still.`);
}
}
class Rabbit extends Animal {
/*
**Generated from extending classes without it's own constructor
constructor(...args) {
super(...args)
}
*/
/*
Constructors in inheriting classes must call super(...), and (!) do it before using this.
like the case of name inherited from Animal class
*/
constructor(name,earthLength){
super(name);//To call parent param
this.earthLength = earthLength;
}
hide(){
alert(`${this.name} hides!`);
}
stop() {
super.stop();//Call parent stop
this.hide();//and then hide
}
}
let rabbit = new Rabbit("White rabbit");
rabbit.run(5);//From parent Animal class
rabbit.stop();//From Rabbit class called from super