21_class类.html 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>Document</title>
  7. </head>
  8. <body>
  9. <script>
  10. // 类的定义
  11. class Person{
  12. // 类的构造函数
  13. constructor(name,age){
  14. this.username = name;
  15. this.age = age;
  16. }
  17. // 类的方法
  18. talk(){
  19. console.log(`我叫${this.username},我今年${this.age}岁`)
  20. }
  21. }
  22. // let p1 = new Person("张三",18);
  23. // console.log(p1.username);
  24. // p1.talk();
  25. // 类的继承
  26. class Teacher extends Person{
  27. constructor(name,age,school){
  28. super(name,age);
  29. this.school = school;
  30. }
  31. // 私有方法
  32. showSchool(){
  33. console.log("我的学校是"+this.school);
  34. }
  35. }
  36. let t1 = new Teacher("张三",18,"清华大学");
  37. console.log(t1.username);
  38. t1.talk();
  39. t1.showSchool();
  40. </script>
  41. </body>
  42. </html>