面向对象

1.类与实例:类的声明,创建实例

1
2
3
4
5
6
7
8
9
10
11
//传统方式:构造函数
function Student(name){
this.name = name;
}

//es6语法
class Student{
constructor(){
this.name = name;
}
}

2.继承的原理:原型链
3.实现继承的方式

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
//借助构造函数实现继承:不能继承原型对象中的方法(部分继承)
function Parent(){
this.name = "parent";
}
function Child(){
Parent.call(this);//或apply
this.age = '18';
}

//借助原型链实现继承:不能实现隔离,修改原型链上的属性就会所有实例都改变
function Parent(){
this.name = "parent";
}
function Child(){
this.age = '18';
}
Child.prototype = new Parent();

//组合方式:构造函数执行2次
function Parent(){
this.name = "parent";
}
function Child(){
Parent.call(this);//或apply
this.age = '18';
}
Child.prototype = new Parent();

//组合优化:此时创建的实例既是child的实例,又是parent的实例,区别不了,实例的constructor指向parent
function Parent(){
this.name = "parent";
}
function Child(){
Parent.call(this);//或apply
this.age = '18';
}
Child.prototype = Parent.prototype;

//最终版
function Parent(){
this.name = "parent";
}
function Child(){
Parent.call(this);//或apply
this.age = '18';
}
//创建中间对象
Child.prototype = Object.create(Parent.prototype)
Child.prototype.constructor = Child;