20_ES5继承.html 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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. // let timer = new Date();
  11. // console.log(timer.getFullYear());
  12. // 创建构造函数
  13. function Person(name,age){
  14. // 初始化属性 一般都是写在构造函数中
  15. this.type = "人";
  16. // 保存构造函数传递参数
  17. this.name = name;
  18. this.age = age;
  19. }
  20. // 构造函数的方法一般写在原型对象中
  21. Person.prototype.say = function(){
  22. console.log(`我是${this.name},我今年${this.age}岁,我是一个人`);
  23. }
  24. // 通过new关键字创建一个实例对象
  25. // let p1 = new Person("张三",18);
  26. // console.log(p1.type);
  27. // p1.say();
  28. // 构造函数继承
  29. function Student(name,age,school){
  30. // 调用父类构造函数
  31. Person.call(this,name,age);
  32. // 初始化属性
  33. this.school = school;
  34. }
  35. // 子类的方法
  36. Student.prototype = new Person();
  37. // 修复constructor指向问题
  38. Student.prototype.constructor = Student;
  39. Student.prototype.saySchool = function(){
  40. console.log(`我是${this.name},我今年${this.age}岁,我是一个人,我去${this.school}上学`);
  41. }
  42. let s1 = new Student("李四",18,"清华大学");
  43. // s1.say();
  44. s1.saySchool();
  45. console.log(s1.constructor);
  46. </script>
  47. </body>
  48. </html>