接上一篇博客 JS 如何实现类
ES6 实现继承的本质其实是用 原型
来完成的
学单词:constructor
extends
super
实现 class
上班族的自我介绍
class Workers {
constructor(name, salary) {
this.name = name
this.salary = salary
}
introduction() {
console.log(`我叫${this.name},我月入${this.salary},满脸笑哈哈哈`)
}
}
const tianmilaozhang = new Workers('甜蜜老张', 1800)
tianmilaozhang.introduction()
// 输出:我叫甜蜜老张,我月入1800,满脸笑哈哈哈
老板画大饼
class Boss {
constructor(name, pay) {
this.name = name
this.pay = pay
}
drawPie() {
console.log(`作为${this.name},我每个月给你发${this.pay},但是项目成了之后,我保证会发1%的盈利份额给你们的!`)
}
}
const yourBoss = new Boss('你的老板', 1800)
yourBoss.drawPie()
// 作为你的老板,我每个月给你发1800,但是项目成了之后,我保证会发1%的盈利份额给你们的!
但是有没有发现,上面两组代码,有 name 这个共同属性呀?| 那我们提取出来吧!
使用类继承「属性」
- 共有属性放在构造函数中
- 子类用
extends
继承父类的东西 - 子类在
构造函数
里使用super()
来获取父类的属性
// 使用继承,提取共有属性
class Person {
constructor(name) { // 把共有属性放在构造函数中
this.name = name
}
}
// 上班族自我介绍
class Workers extends Person { // 用 extends 继承父类的属性
constructor(name, salary) {
super(name) // 共有属性用 super() 获取
this.salary = salary
}
introduction() {
console.log(`我叫${this.name},我月入${this.salary},满脸笑哈哈哈`)
}
}
const tianmilaozhang = new Workers('甜蜜老张', 1800)
tianmilaozhang.introduction()
// 老板画大饼
class Boss extends Person { // 用 extends 继承父类的属性
constructor(name, pay) {
super(name) // 共有属性用 super() 获取
this.pay = pay
}
drawPie() {
console.log(`作为${this.name},我每个月给你发${this.pay},但是项目成了之后,我保证会发1%的盈利份额给你们的!`)
}
}
const yourBoss = new Boss('你的老板', 1800)
yourBoss.drawPie()
// 我叫甜蜜老张,我月入1800,满脸笑哈哈哈
// 作为你的老板,我每个月给你发1800,但是项目成了之后,我保证会发1%的盈利份额给你们的!
同样,函数也可以「继承」
- 共有的函数,直接写在外面
- 子类直接调用,无需使用
super
// 使用继承,提取共有属性
class Person {
constructor(name) {
this.name = name
}
drink() { // 共有的函数,直接写外面
console.log('我会喝水')
}
}
// 上班族自我介绍
class Workers extends Person {
constructor(name, salary) {
super(name)
this.salary = salary
}
introduction() {
console.log(`我叫${this.name},我月入${this.salary},满脸笑哈哈哈`)
}
}
const tianmilaozhang = new Workers('甜蜜老张', 1800)
tianmilaozhang.introduction()
tianmilaozhang.drink() // 直接调用
// 老板画大饼
class Boss extends Person {
constructor(name, pay) {
super(name)
this.pay = pay
}
drawPie() {
console.log(`作为${this.name},我每个月给你发${this.pay},但是项目成了之后,我保证会发1%的盈利份额给你们的!`)
}
}
const yourBoss = new Boss('你的老板', 1800)
yourBoss.drawPie()
yourBoss.drink() // 直接调用
/* 我叫甜蜜老张,我月入1800,满脸笑哈哈哈
我会喝水
作为你的老板,我每个月给你发1800,但是项目成了之后,我保证会发1%的盈利份额给你们的!
我会喝水 */
完。