(一)class的目的就是让定义类更简单
我们先回顾用函数实现Peopel
的方法:
function Peopel(name) {
this.name = name;
}
Peopel.prototype.hello = function () {
console.log('Hello, ' + this.name + '!');
}
如果用新的class关键字来编写Peopel
,可以这样写:
// 类的开头得大写
class Peopel {
// 构造器构造属性
constructor(name) {
this.name = name;
}
// 方法
hello() {
console.log('Hello, ' + this.name + '!');
}
}
比较一下就可以发现,class的定义包含了构造函数constructor
和定义在原型对象上的函数hello()(注意没有function关键字),这样就避免了Student.prototype.hello = function () {...}
这样分散的代码。
// 创建一个人的实例
var xiaoming = new Peopel('小明');
console.log(xiaoming.name); // 小明
xiaoming.hello(); // hello,小明!
(二)类的继承
继承父类,通过extends来实现,方法可以直接调用,属性需要调用super去执行
// 父类
class Peopel {
constructor(name) {
this.name = name;
}
eat() {
console.log(`${this.name} eat something`);
}
}
// 子类的继承Peopel
// 注意Student的定义也是class关键字实现的,而extends则表示原型链对象来自Peopel
class Student extends Peopel {
constructor(name, number) {
super(name); //调用super(),代替父类构造函数,初始化与父类共同的属性
this.number = number;
}
information() {
console.log(`姓名:${this.name}, 学号:${this.number}`)
}
}
// 子类的继承Peopel
class Teach extends Peopel {
constructor(name, major) {
super(name);
this.major = major;
}
teach() {
console.log(`姓名:${this.name}, 主修:${this.major}`)
}
}
实例
// 创建一个学生的实例
const newStudent = new Student('wendy', 101);
console.log(newStudent.name); // wendy
console.log(newStudent.number); // 101
newStudent.information(); // 姓名:wendy,学号:101
// 创建一个老师的实例
const newTeacher = new Teach('温老师', '语文');
console.log(newTeacher.name); // 温老师
console.log(newTeacher.major); // 语文
newTeacher.teach(); // 姓名:温老师,主修:语文