25_Class.html 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. // 类的定义 (ES6)使用class关键字
  11. class Person{
  12. //constructor 构造函数 用于初始化对象的属性
  13. constructor(userName,age){
  14. this.userName = userName;
  15. this.age = age;
  16. }
  17. // 为类添加方法
  18. sayName(){
  19. console.log(`我是${this.userName},今年${this.age}岁`);
  20. }
  21. }
  22. // 调用类的构造函数
  23. // let p1 = new Person("张三",20);
  24. // console.log(p1.userName,p1.age);
  25. // // 调用方法
  26. // p1.sayName();
  27. // 类的继承 (ES6)使用extends关键字
  28. class Student extends Person{
  29. constructor(userName,age,school){
  30. // 调用父类的构造函数 继承父类的属性
  31. super(userName,age);
  32. this.school = school;
  33. }
  34. // 为子类添加方法
  35. saySchool(){
  36. console.log(`我是${this.userName},我来自${this.school}`);
  37. }
  38. }
  39. // 调用子类的构造函数
  40. let s1 = new Student("李四",18,"清华大学");
  41. console.log(s1.userName,s1.age,s1.school);
  42. // 调用方法
  43. s1.sayName();
  44. s1.saySchool();
  45. </script>
  46. </body>
  47. </html>