21_class类.html 1.2 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. // 初始化属性
  15. this.name = name;
  16. this.age = age;
  17. }
  18. // 方法
  19. say(){
  20. console.log(`我是${this.name},我今年${this.age}岁`);
  21. }
  22. }
  23. // let p1 = new Person("张三",18);
  24. // p1.say();
  25. // 类的继承
  26. class Student extends Person{
  27. constructor(name,age,school){
  28. // 调用父类构造函数
  29. super(name,age);
  30. // 初始化属性
  31. this.school = school;
  32. }
  33. // 方法
  34. saySchool(){
  35. console.log(`我是${this.name},我今年${this.age}岁,我是一个人,我去${this.school}上学`);
  36. }
  37. }
  38. let s1 = new Student("李四",18,"清华大学");
  39. s1.say();
  40. s1.saySchool();
  41. </script>
  42. </body>
  43. </html>