es6中的class使用与继承

(一)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(); // 姓名:温老师,主修:语文
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值