Blogger Information
Blog 21
fans 0
comment 0
visits 10042
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
实例演示class类与extends,super等的用法
放手去爱
Original
493 people have browsed it

class类的用法

  1. // 1. 类声明
  2. let User = class {
  3. // 构造函数:声明属性
  4. constructor(uname, email) {
  5. // (1) 属性
  6. this.uname = uname
  7. this.email = email
  8. }
  9. // (2) 方法
  10. say() {
  11. return `${this.uname}: ( ${this.email} )`
  12. }
  13. // (3) 静态成员
  14. static nation = 'CHINA'
  15. }
  16. // 2. 类的实例化
  17. const user = new User('潘金莲', 'pjl@qq.com')
  18. console.log(user.say())
  19. console.log(User.nation)
  20. console.log('-----------------------')

extends,super等的用法

  1. // ? 继承
  2. class Child extends User {
  3. constructor(uname, email, sex) {
  4. // super 调用父类成员
  5. super(uname, email)
  6. // 子类扩展的属性
  7. this.sex = sex
  8. }
  9. say() {
  10. // super.say() 父类中的say()
  11. return `${super.say()}, (${this.sex})`
  12. }
  13. }
  14. const child = new Child('灭绝', 'mj@qq.com', '女')
  15. console.log(child.say())
  16. // ! 在类中使用"访问器属性"
  17. const Stu = class {
  18. // 私有属性: 在属性前加 #
  19. #age = 18
  20. // 访问器属性
  21. // 1. 读, 获取器get
  22. get age() {
  23. return this.#age
  24. }
  25. // 2. 写, 设置器 set
  26. set age(age) {
  27. if (age >= 18 && age <= 100) {
  28. this.#age = age
  29. } else {
  30. console.log('年龄必须在18-100之间')
  31. }
  32. }
  33. }
  34. let stu = new Stu()
  35. console.log('age = ', stu.age)
  36. // stu.age = 120
  37. stu.age = 30
  38. console.log('age = ', stu.age)
Correcting teacher:PHPzPHPz

Correction status:qualified

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post