继承
# 继承
// class Car {
// static color = 1;
// constructor(price) {
// this.price = price;
// }
// test() {
// console.log(this.price);
// }
// }
// class Cruze extends Car {
// constructor(price) {
// super(price)
// }
// }
// console.log(Cruze.color);
// const cruze = new Cruze(3000);
// cruze.test();
'use strict';
function Car(price) {
this.price = price;
}
Car.color = 'red';
Car.prototype.test = function () {
console.log(this.price);
};
function Cruze(price) {
Car.call(this, price);
}
//es5继承静态属性
var staticKeys = Object.entries(Car);
for (var i = 0; i < staticKeys.length; i++) {
var key = staticKeys[i][0];
var value = staticKeys[i][1];
Cruze[key] = value;
}
// Cruze.prototype = Car.prototype; ❌
// Cruze.prototype = new Car(); ❌ 构造函数
// var _proto = Object.create(Car.prototype);
// _proto.constructor = Cruze;
Cruze.prototype = Object.create(Car.prototype, {
constructor: {
value: Cruze,
writable: false,
},
test: {
value: function () {},
},
});
// Cruze.prototype.constructor = function () { };
// Cruze.prototype = _proto;
console.log(Cruze['color']);
var cruze = new Cruze('3000');
cruze.test();
console.log(cruze);
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
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
更新时间: 3/15/2022, 12:28:01 AM