-
Notifications
You must be signed in to change notification settings - Fork 4
/
07.继承.js
73 lines (67 loc) · 1.37 KB
/
07.继承.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
// 1. 原型链继承 + 构造函数继承 = 组合继承
function Animal(name){
this.name = name
}
Animal.prototype.say=function(hi){
console.log(this.name + hi)
}
function Cat(...args){
Animal.call(this,...args)
}
Cat.prototype = new Animal()
let c = new Cat('Tom')
console.log(c.name)
c.say('miao')
// 2. 原型式继承:Object.create
// 自己实现一个create
let A = {
name:'old'
}
let B = Object.create(A,{
name:{
value:"ccc"
}
})
console.log(B.name)
// 思考如何模拟????TODO
function create(o,des = {}){
function fn(){}
fn.prototype = o
Object.setPrototypeOf(fn,o,des)
return new fn()
}
let C = create(A,{
name:{
value:'xxxxxxx'
}
})
console.log(C.name)
// 3. 寄生式继承
function createAnother(original){
var clone = Object(original)
clone.sayHi = function(){
console.log('hi')
}
return clone
}
let d = createAnother(A)
console.log(d.name)
d.sayHi()
// 4.
function inheritProperty(subType,superType){
var prototype = Object(superType.prototype)
prototype.constructor = prototype
subType.prototype = prototype
}
function superType(){
this.name = 'super'
}
superType.prototype.height = '19'
function subType(){
superType.call(this)
this.age = '15'
}
inheritProperty(subType,superType) //
let s1 =new subType()
console.log(s1.name)
console.log(s1.height)