-
Notifications
You must be signed in to change notification settings - Fork 0
/
classical-inherit.js
95 lines (58 loc) · 1.6 KB
/
classical-inherit.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
81
82
83
84
85
86
87
88
89
90
91
92
93
// classical inherit
// In #JavavScript classical inherit means inherit in classes.
function Parent () {
this.wasBornParent = true;
}
function Child () {
this.isChildClassUsed = true;
}
function inherit (C, P) {
C.prototype = new P();
}
inherit(Child, Parent);
var object = new Child();
console.log(object.wasBornParent, object.isChildClassUsed); // true true
// minus: - inherit specific parent's properties.
// - can't use params.
// classical inherit #2
function Parent (name) {
this.name = name || 'vlad';
}
function Child () {
this.surname = 'khvostov';
// Call parent constructor like method for this object
Parent.apply(this, arguments)
}
var object = new Child('Alex');
console.log(object) // Child {surname: "khvostov", name: "Alex"}
// minuses: the parent prototype is lost
// pluses: child instance gets real copies their properties from parent's constructor.
// classical inherit #3 (unites two examples)
function Parent (name) {
this.name = name || 'vlad';
}
Parent.prototype.sayHi = function() {
console.log('Hi ' + this.name)
};
function Child () {
Parent.apply(this, arguments)
}
Child.prototype = new Parent();
var object = new Child('Alex');
console.log(object.sayHi()); // Hi Alex
// minuses: performance degradation
// classical inherit #4
function inherit(C, P){
C.prototype = P.prototype
}
// minuses: copies only prototypes.
// classical inherit # (preferred way)
var inherit = (function () {
var F = function () {};
return function (C, P) {
F.prototype = P.prototype;
C.prototype = new F();
C.uber = P.prototype;
C.prototype.constructor = C;
}
})();