-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinheritance.js
80 lines (63 loc) · 1.21 KB
/
inheritance.js
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/**
* This shows the different types of inheritance in Javascript
* - Classical inheritance
* - Prototypical inheritance [Recommended]
*
* Favor object composition over inheritance - Erric Elliot
*/
/**
* Classical inheritance
*/
function Animal(name) {
this.name = name;
}
Animal.prototype.getName = function() {
return this.name;
};
function Dog() {
Animal.apply(this, arguments);
}
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
/***** is this ☝ just crazy :( ***/
/**
* Prototypical inheritance
*/
const Vehicle = {
create: function(name) {
var self = this;
self.name = name;
return self;
},
getName: function() {
return this.name;
}
};
const Bus = Object.create(Vehicle);
Bus.create = function(name) {
return Vehicle.create.call(this, name);
};
/**
* usage
*/
let saloonCar = Bus.create('Honda');
// saloonCar.getName();
/***** better right ☝ I know :) ***/
class Square {
constructor(size) {
this.size = size;
}
area() {
return Math.pow(this.size, 2);
}
}
class Rectangle extends Square {
constructor(lenth, breadth) {
super(length);
this.length = length;
this.breadth = breadth;
}
area() {
return this.length * this.breadth;
}
}