-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinherit.html
85 lines (67 loc) · 1.61 KB
/
inherit.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>js 模拟继承</title>
</head>
<body>
<script>
// 1 自身的属性
// 2 原型上的属性
function Animal(name){
this.name = name
this.eat = function(){
console.log(this.name + ' is eating')
}
}
Animal.prototype.run = function(){
console.log(this.name + ' is runing')
}
const a = new Animal('aaa')
console.log(a)
function Cat(){
Animal.call(this,'cat')
}
// a.__proto__ = Animal.prototype
// a.run()
// Cat.prototype.__proto__ = Animal.prototype
// Cat.prototype = new Animal()
// function f(){}
// f.prototype = Animal.prototype
// Cat.prototype = new f()
Cat.prototype = Object.create(Animal.prototype)
Cat.prototype.constructor = Cat
const cat = new Cat()
console.log(cat)
cat.run()
// cat.__proto__ => Cat.prototype
// Cat.prototype.__proto__ => Aniaml.prototype
// es6 class
class Parent {
constructor(name){
this.name = name
this.eat = function(){
console.log(this.name + ' is eating')
}
}
run(){
console.log(this.name + ' is runing')
}
}
class Child extends Parent{
constructor(){
super('child')
}
}
const p = new Parent('parent')
console.log(p)
p.eat()
const c = new Child()
console.log(c)
c.eat()
c.run()
</script>
</body>
</html>