手动实现ES6继承
# 借助构造函数实现
function parent1() {
this.name = 'parent1'
}
function child1() {
this.name = 'child1'
this.age = 18
// 继承this上下文
parent1.call(this)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
// 原型链继承
function parent2() {
this.name = 'parent1'
}
function child2() {
this.name = 'child1'
this.age = 18
}
child1.prototype = new parent2()
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
共享了原型对象地址
组合方式解决
function parent3() {
this.name = 'parent1'
}
function child3() {
this.name = 'child1'
this.age = 18
parent3.call(this)
}
child3.prototype = new parent3()
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
缺点:重复实例化了 而且后面的原型链中方法用不着
child3.prototype = parent3.prototype
1
问题: 会导致实例的__proto__.constructor
指向parent3
child3.prototype = Object.create(parent3.prototype)
上次更新: 2022/07/03, 15:02:21