-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclasses.js
More file actions
64 lines (47 loc) · 1.27 KB
/
classes.js
File metadata and controls
64 lines (47 loc) · 1.27 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
58
59
60
61
62
//Class inheritance is a way for one class to extend another class
//So we can create new functionality
class Animal {
//Pass a name variable when initializing
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.`);
}
}
let animal = new Animal('My animal');
//Rabbit example
class Rabbit extends Animal {
hide () {
alert(`${this.name} hides!`);
}
//Arrow functions have no super
//Unless called from outer function in this case setTimeout
stop(){
setTimeout(()=>super.stop(),1000);
/*
** setTimeout(function() { super.stop() }, 1000)
** returns Unexpected super
*/
}
}
let rabbit = new Rabbit("White Rabbit");
rabbit.run(5);//Method from extended class
rabbit.hide();//White rabbit hides
//Anything is allowed after the extend
//See example
//Extends a function that creates a class
function f(phrase) {
return class {
sayHi() { alert(phase); }
};
}
class User extends f('Hello'){}
new User().sayHi();
//Here class User inherits from the result of f("Hello").