ES5面向对象
# ES5 面向对象
//面向对象封装
function Student(props) {
// 构造函数 (构造函数内定于属性。尊从首字母大写的约定)
this.name = props.name || "匿名"; // 默认‘匿名’
this.grade = props.grade || 1;
}
Student.prototype.hello = function () {
// 在构造函数的原型上定义方法
console.log("你好," + this.name + "同学,你在" + this.grade + "年级");
};
//使用
function createStudent(props) {
// 对于new构造函数的封装,其优点:一是不需要new来调用,二是参数灵活
return new Student(props || {}); // 通过new创建构造函数,并传入参数/属性
}
var niming = createStudent();
niming.hello();
var xiaoming = createStudent({
name: "小明",
grade: 2,
});
xiaoming.hello();
//继承
function inherits(Child, Parent) {
// 继承的封装方法 inherits(子类, 父类)
var F = function () {}; // 定义空方法F
F.prototype = Parent.prototype; //F原型指向父类原型
Child.prototype = new F(); // 子类原型指向 new F() 方法
Child.prototype.constructor = Child; // 修正子类原型上的构造函数为子类本身函数
}
function PrimaryStudent(props) {
//定义子类 构造函数
Student.call(this, props); // 修正this指向
this.age = props.age || 8; //新增子类属性
}
inherits(PrimaryStudent, Student); //调用继承封装方法实现继承
PrimaryStudent.prototype.getAge = function () {
//对子类添加方法
console.log(this.name + "同学,你今年" + this.age + "岁");
};
//使用继承后的
function createPrimaryStudent(props) {
// 对于new构造函数的封装,其优点:一是不需要再new来调用,二是参数灵活
return new PrimaryStudent(props || {}); // 通过new创建构造函数,并传入参数/属性
}
var xiaohong = createPrimaryStudent({
name: "小红",
grade: 3,
age: 10,
});
xiaohong.hello();
xiaohong.getAge();
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
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
编辑 (opens new window)
上次更新: 2023/09/06, 15:09:00