-
Notifications
You must be signed in to change notification settings - Fork 7
/
ex5-extends.js
101 lines (79 loc) · 2.05 KB
/
ex5-extends.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
94
95
96
97
98
99
100
101
// * ================================================================================ class
{
class MyBase {
constructor(val) {
this.val = val;
console.log('base_init', val, this.val);
}
log() {
console.log('base_val', this.val);
}
solid() {
console.log('solid_val', this.val);
}
}
class MyExt extends MyBase {
constructor(val) {
super(val);
this.val = 'ext' + val;
console.log('init', val, this.val);
}
log() {
console.log('ext_val', this.val);
}
}
// * ----------------
const inst = new MyExt(233);
inst.log();
inst.solid();
// * ----------------
console.log([
MyExt.prototype === inst.__proto__,
MyExt.prototype === Object.getPrototypeOf(inst),
MyExt.prototype.constructor === MyExt,
MyExt.prototype.__proto__ === MyBase.prototype,
]);
// * ----------------
}
console.log('--------');
// * ================================================================================ es5
{
function MyBase(val) {
this.val = val;
console.log('base_init', val, this.val);
}
MyBase.prototype.log = function () {
console.log('base_val', this.val);
};
MyBase.prototype.solid = function () {
console.log('solid_val', this.val);
};
// * ----------------
const es5extends = (subFn, superFn) => {
// * 原型链寄生组合继承
subFn.prototype = Object.create(superFn.prototype);
subFn.prototype.constructor = subFn;
};
// * ----------------
function MyExt(val) {
// * 模拟 super
MyBase.call(this, val);
this.val = 'ext' + val;
console.log('init', val, this.val);
}
es5extends(MyExt, MyBase);
MyExt.prototype.log = function () {
console.log('ext_val', this.val);
};
// * ----------------
const inst = new MyExt(233);
inst.log();
inst.solid();
// * ----------------
console.log([
MyExt.prototype === inst.__proto__,
MyExt.prototype === Object.getPrototypeOf(inst),
MyExt.prototype.constructor === MyExt,
MyExt.prototype.__proto__ === MyBase.prototype,
]);
}