面向对象

课程思维导图

面向对象.png

Q:类的声明有哪些方式,如何实例化?

1
2
3
4
5
6
7
8
9
10
11
12
// 构造函数法
function Animal() {this.name = "name"};
------------------------------------------
// ES6类
class Animal {
constructor () {
this.name = "name";
}
}
------------------------------------------
// 类的实例化
new Animal

Q:继承的本质是?

原型链

Q:如何实现继承?

一、借助构造函数实现继承

1
2
3
4
5
6
7
8
9
10
11
/**
* 原理:改变父类构造函数运行时的this指向,从而实现了继承
* 不足:只实现部分继承,父类原型对象上的属性/方法子类取不到。
*/
function Parent1 () {
this.name="parent1"
}
function Child1 () {
Parent.call(this);
this.type = "child1";
}

二、借助原型链实现继承

1
2
3
4
5
6
7
8
9
10
11
/**
* 原理:原理:new Child2 => new Child2.__proto__ === Child2.prototype => new Parent2() => new Parent2().__proto__ === Parent2.prototype,所以实现了Child2实例继承自Parent2的原型对象。
* 不足:多个实例共用一个父类的实例对象,修改其中一个实例上的引用对象,会对其他实例造成影响。
*/
function Parent2 () {
this.name = "parent2";
}
function Child2 () {
this.name = "child2";
}
Child2.prototype = new Parent2();

三、组合方式实现继承

1
2
3
4
5
6
7
8
9
10
11
/**
* 优点:弥补了原型链继承的缺点,实例修改父类上的引用对象时,不会对其他实际造成影响
* 不足:父级构造函数执行两次,子类构造函数指向父类构造函数
*/
function Parent3 () {
this.name = "parent3";
}
function Child3 () {
Parent3.call(this);
}
Child3.prototype = new Parent3();

四、组合方式优化

1
2
3
4
5
6
7
8
9
10
11
/**
* 组合方式优化
* 不足:子类构造函数仍旧指向父类构造函数
*/
function Parent4 () {
this.name = "parent4";
}
function Child4 () {
Parent4.call(this);
}
Child4.prototype = Parent4.prototype;

五、组合继承方式的完美方案

1
2
3
4
5
6
7
8
9
10
11
/**
* 优点:Object.create()生成中间对象,隔离了子/父类原型对象,使之不会互相影响。
*/
function Parent5 () {
this.name = "parent5";
}
function Child5 () {
Parent5.call(this);
}
Child5.prototype = Object.create(Parent5.prototype);
Child5.prototype.constructor = Child5;