当前位置: 代码迷 >> 综合 >> 令人振奋的Class(下):继承和实战代码示例
  详细解决方案

令人振奋的Class(下):继承和实战代码示例

热度:21   发布时间:2023-10-22 10:23:29.0
class User {
    constructor(n){this._name = n;}showme(){console.log(this._name);}
}// 继承
class student extends User {
    constructor(sname){super(sname);}
}// 实例化子类
let s = new student("lily");
s.showme();//打印:lily
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
s._name;// 也能访问,还没有私有属性的概念
  
  • 1
  • 1

实战演练 
1.有个User对象(基类) 
2.里面包含了teacher和student类,都统一继承User 
3.我的名字叫jack,如果我是学生并且也是一个对象,则继承student 
这个业务的JS代码该怎么写?

class User {
    constructor(n){this._name = n;}showme(){console.log(this._name);}static get Student(){// 返回一个继承User的类return class extends User{
    constructor(sname){super("学生的名字是:"+sname);}}}static get Teacher(){// 返回一个继承User的类return class extends User{
    constructor(tname){super("老师的名字是:"+tname);}}}
}//继承
class jack extends User.Student {
    constructor(sname){super(sname);}
}
let s = new jack("杰克");
s.showme();//学生的名字是:杰克
  
  • 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
  • 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

换成老师

class jack extends User.Teacher {
    constructor(sname){super(sname);}
}
let s = new jack("杰克");
s.showme();//老师的名字是:杰克
  相关解决方案