-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinheritance.js
executable file
·44 lines (33 loc) · 969 Bytes
/
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
function Shape() {}
function Circle() {}
// Prototypical inheritance
Circle.prototype = Object.create(Shape.prototype);
Circle.prototype.constructor = Circle;
function Rectangle(color) {
// To call the super constructor
Shape.call(this, color);
}
// Method overriding
Shape.prototype.draw = function() {}
Circle.prototype.draw = function() {
// Call the base implementation
Shape.prototype.draw.call(this);
// Do additional stuff here
}
// Don't create large inheritance hierarchies.
// One level of inheritance is fine.
// Use mixins to combine multiple objects
// and implement composition in JavaScript.
const canEat = {
eat: function() {}
};
const canWalk = {
walk: function() {}
};
function mixin(target, ...sources) {
// Copies all the properties from all the source objects
// to the target object.
Object.assign(target, ...sources);
}
function Person() {}
mixin(Person.prototype, canEat, canWalk);