20_继承.html 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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. function Person(userName, userAge) {
  11. this.userName = userName;
  12. this.userAge = userAge;
  13. // this.talk = function () {
  14. // console.log(`大家好我叫${this.userName}今年${this.userAge}岁了`);
  15. // }
  16. }
  17. Person.prototype.loveCoding = "四福";
  18. Person.prototype.talk = function () {
  19. console.log(`大家好我叫${this.userName}今年${this.userAge}岁了`);
  20. }
  21. // var p1 = new Person('张三', 18);
  22. // p1.talk();
  23. // 构造继承 无法继承原型上的属性和方法
  24. // function Student(userName,userAge,school) {
  25. // Person.call(this,userName,userAge);
  26. // this.school = school;
  27. // }
  28. // let s1 = new Student('张三',18,'清华大学');
  29. // console.log(s1.userName);
  30. // console.log(s1.loveCoding);
  31. // 原型继承
  32. function Student(userName,userAge,school) {
  33. this.userName = userName;
  34. this.userAge = userAge;
  35. this.school = school;
  36. }
  37. Student.prototype = new Person();
  38. let s1 = new Student('张三',18,'清华大学');
  39. console.log(s1.loveCoding);
  40. console.log(s1.userName);
  41. s1.talk();
  42. </script>
  43. </body>
  44. </html>