forked from yeyan1996/practical-javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclass.js
77 lines (68 loc) · 1.71 KB
/
class.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
//简单模拟ES6的class实现
// class Animal {
// constructor(name) {
// this.name = name
// }
//
// sleep() {
// console.log('animal is sleeping')
// }
//
// static staticFunc() {
// console.log('staticFunc')
// }
// }
//
// class Dog extends Animal {
// constructor(name, color) {
// super(name)
// this.color = color
// }
//
// barking() {
// console.log('wang!')
// }
// }
//
// let brownTeddy = new Dog('teddy', 'brown')
// Dog.staticFunc()
// console.log(brownTeddy)
// brownTeddy.sleep()
// brownTeddy.barking()
function Animal(name) {
this.name = name
}
Animal.staticFunc = function () {
console.log('staticFunc')
}
Animal.prototype.sleep = function () {
console.log('animal is sleeping')
}
function Dog(name, color) {
Animal.call(this, name)
this.color = color
}
//寄生组合式继承 + 构造函数之间的继承
function inherit(subType, superType) {
//由于JavaScript引用类型和函数按值传递的特性,不能改变subType的引用地址
subType.prototype = Object.create(superType.prototype, {
constructor: {
enumerable: false,
configurable: true,
writable: true,
value: superType.constructor
}
})
//子构造函数继承父构造函数(子类继承父类的静态方法和静态属性)
Object.setPrototypeOf(subType, superType)
}
inherit(Dog, Animal)
//需要在继承之后再往Dog中添加原型方法,否则会被覆盖掉
Dog.prototype.barking = function () {
console.log('wang!')
}
let brownTeddy = new Dog('teddy', 'brown')
Dog.staticFunc()
console.log(brownTeddy)
brownTeddy.sleep()
brownTeddy.barking()