24_构造函数.html 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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. // 构造函数 比如 Array、Object、Function、String、Number、Boolean、Date 等
  11. // console.log(Array);
  12. // 也可以自定构造函数
  13. function Person(userName,age) {
  14. this.userName = userName;
  15. this.age = age;
  16. }
  17. // 为构造函数添加方法
  18. Person.prototype.sayName = function(){
  19. // console.log("我是"+this.userName+",我今年"+this.age+"岁");
  20. console.log(`我是${this.userName},我今年${this.age}岁`);
  21. }
  22. // 调用构造函数
  23. // var p1 = new Person("张三",18);
  24. // // console.log(p1.userName,p1.age);
  25. // // 调用方法
  26. // p1.sayName();
  27. // var p2 = new Person("李四",20);
  28. // p2.sayName();
  29. // 用继承的方式生成一个新的构造函数
  30. function Student(userName,age,school) {
  31. // 调用父类的构造函数 继承父类的属性
  32. Person.call(this,userName,age);
  33. this.school = school;
  34. }
  35. //继承父类的方法
  36. Student.prototype = new Person();
  37. // 为子类添加方法
  38. Student.prototype.saySchool = function(){
  39. console.log(`我来自${this.school}`);
  40. }
  41. // 调用子类的构造函数
  42. var s1 = new Student("王五",22,"清华大学");
  43. console.log(s1.userName,s1.age);
  44. // 调用方法
  45. s1.sayName();
  46. s1.saySchool();
  47. // ES中没有类,只有构造函数和原型 模拟类
  48. </script>
  49. </body>
  50. </html>