-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclasses.js
More file actions
55 lines (46 loc) 路 1.35 KB
/
Copy pathclasses.js
File metadata and controls
55 lines (46 loc) 路 1.35 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
export default () => {
class Animal {
static isAnAnimal (maybeAnAnimal) {
return '_animal' in maybeAnAnimal && Boolean(maybeAnAnimal._animal)
}
// initialisation of class properties
_animal = true
type = 'unknown'
constructor ({ name = 'unnamed' }) {
this.name = name
}
shout () {
const { name } = this
console.log(`Hey! I'm ${this.name}`)
}
// Allows to automatically binds this on eat method
eat = () => {
console.log(`${this.name} just ate.`)
}
}
class Dog extends Animal {
constructor (options) {
super(options)
this.type = 'dog'
}
shout () {
console.log('Waf!')
super.shout() // calls the method from the parent class
}
}
const aSadPet = new Animal({})
console.log(
`Is ${aSadPet.name} an animal? ${Animal.isAnAnimal(aSadPet) ? `yes it's a ${aSadPet.type}` : 'no'}`
) // Is unnamed an animal? yes it's a unknown
aSadPet.shout() // Hey! I'm unnamed
aSadPet.eat() // unnamed just ate.
const fluffykins = new Dog({ name: 'Fluffykins' })
console.log(
`Is ${fluffykins.name} an animal? ${Animal.isAnAnimal(fluffykins) ? `yes it's a ${fluffykins.type}` : 'no'}`
) // Is Fluffykins an animal? yes it's a dog
fluffykins.shout()
// Waf!
// Hey! I'm Fluffykins
setTimeout(fluffykins.eat)
// Fluffykins just ate.
}