20_继承.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. function Person(name,age){
  12. this.username = name;
  13. this.age = age;
  14. }
  15. // 原型上写方法
  16. Person.prototype.talk = function(){
  17. console.log(`我叫${this.username},我今年${this.age}岁`)
  18. }
  19. // 继承
  20. function Teacher(name,age,school ){
  21. // 调用父类的构造函数
  22. Person.call(this,name,age);
  23. this.school = school;
  24. }
  25. // 继承父类的方法
  26. Teacher.prototype = Person.prototype;
  27. // 修复构造函数指向
  28. Teacher.prototype.constructor = Teacher;
  29. // 自己独有的方法
  30. Teacher.prototype.showSchool = function(){
  31. console.log(`我是${this.username},我来自${this.school}`)
  32. }
  33. // 实例化对象
  34. let t1 = new Teacher("王五",30,"清华大学");
  35. console.log(t1.username)
  36. t1.talk();
  37. t1.showSchool();
  38. console.log(t1.constructor);
  39. </script>
  40. </body>
  41. </html>