Javascript继承方式

构造函数继承

Parent: 父对象
Child: 子对象

构造函数绑定

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function Parent() {
this.country = 'shanghai';
}
function Child(name, age) {
// call 或者 apply
// call([对象名], arg1, arg2, arg3, ...) 第一个是对象,后续参数是传入该函数的值
// apply([对象名], [arg1, arg2, arg3, ...]) 第一个是对象, 第二个是数组,这个数组就是该函数的参数(arguments)
Parent.apply(this, arguments)
this.name = name;
this.age = age;
}
let child = new Child('jesse', 26)
console.log(child.country)

prototype模式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function Parent() {
this.country = 'shanghai';
}
function Child(name, age) {
this.name = name;
this.age = age;
}
let Child.prototype = new Parent()
// 需手动指定Child的constructor
Child.prototype.constructor = Child
let child = new Child('jesse', 26)
console.log(Child.prototype.constructor == Parent)
console.log(child.country)

直接继承prototype

1
2
3
4
5
6
7
8
9
10
11
function Parent() {}
function Child() {}
Parent.prototype.country = 'shanghai'
Child.prototype = Parent.prototype
Child.prototype.constructor = Child
let child = new Child()
console.log(child.country)
// 会同时改变Parent.prototype
console.log(Parent.prototype.constructor == Child)

利用空对象

1
2
3
4
5
6
7
8
9
10
11
12
13
function Parent() {}
function Child() {}
// 空对象
let F = function() {}
F.prototype = Parent.prototype
Child.prototype = new F()
Child.prototype.constructor = Child
let child = new Child()
console.log(child.country)
console.log(Parent.prototype.constructor)

封装为方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function extend(C, P) {
let F = function() {}
F.prototype = P.prototype
C.prototype = new F()
C.prototype.constructor = C
// 为子对象设一个uber属性,这个属性直接指向父对象的prototype属性,可以直接调用父对象的方法,为了实现继承的完备性,纯属备用性质
C.uber = P.prototype
}
function Parent() {}
function Child() {}
Parent.prototype.country = 'shanghai'
extend(Child, Parent)

拷贝继承

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 将父对象的prototype对象中的属性,--拷贝给Child对象的prototype对象
function extend(C, P) {
let p = P.prototype
let c = C.prototype
for (let k in p) {
c[k] = p[k]
}
c.uber = p
}
function Parent() {}
function Child() {}
Parent.prototype.country = 'shanghai'
extend(Child, Parent)

非构造函数继承

0%