ES6 之 Class 继承

ES6 中引入的 Class 类实质上是 JavaScript 现有的基于原型的继承的语法糖。类语法不会为 JavaScript 引入新的面向对象的继承模型。


Class / 继承

构造函数

1
2
3
4
5
6
7
8
9
10
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}

sayHello() {
console.log( `hello, ${this.name}, i am ${this.age} years old`);
}
}



ES5 原型写法

1
2
3
4
5
6
7
8
9
10
function Person(name, age) {
this.name = name;
this.age = age;
}

Person.prototype.sayHello = function () {
console.log( `hello, ${this.name}, i am ${this.age} years old`);
};

var p = new Person('hunger', 2);


静态方法

1
2
3
4
5
6
7
8
class EventCenter {
static fire() {
return 'fire';
}
static on(){
return 'on'
}
}



等同于 ES5

1
2
3
4
function EventCenter(){
}
EventCenter.fire = function(){}
EventCenter.on = function(){}


继承

外部使用 extends,内部使用 super() 获取基类的属性。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// 基类
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}

sayHello() {
console.log(`hello, ${this.name}, i am ${this.age} years old`);
}
}

// 继承
class Student extends Person {
constructor(name, age, score) {
super(name, age);
this.score = score;
}

sayScore() {
console.log(`hello, ${this.name}, i am ${this.age} years old,
i get ${this.score}`);
}
}


编程的套路

构造器模式

面向对象方式的构造器模式。

ES5

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<script>
function Student(name, gender, score) {
this.name = name;
this.gender = gender;
this.score = score;
this.quality = 100;

this.sumScore = function () {
return this.score + this.quality;
}
}

var evenyao = new Student('evenyao', '男', 89);
var iu = new Student('iu', '女', 40);

console.log(evenyao.name, evenyao.sumScore())
console.log(iu.name, iu.sumScore())
</script>


ES6

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<script>
class Student {
constructor(name, gender, score) {
this.name = name;
this.gender = gender;
this.score = score;
this.quality = 100;
}

sumScore() {
return this.score + this.quality;
}
}

var evenyao = new Student('evenyao', '男', 89);
var iu = new Student('iu', '女', 40);

evenyao.score = 100;
console.log(evenyao.name, evenyao.sumScore())
console.log(iu.name, iu.sumScore())
</script>


原型模式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<script>
function Student(name, gender, score) {
this.name = name;
this.gender = gender;
this.score = score;
this.qulity = 100;
}

Student.prototype.sumScore = function () {
return this.score + this.qulity;
};

var evenyao = new Student('evenyao', '男', 89);
var iu = new Student('iu', '女', 40);

console.log(evenyao.name, evenyao.sumScore());
console.log(iu.name, iu.sumScore());
</script>
本文结束  感谢您的阅读
0%