22.类.html 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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. * 构造函数
  12. * new 实例化对象
  13. * this指向当前对象本身
  14. * 首字母大写
  15. * 自带了prototype 原型对象 和 constructor 构造器
  16. *
  17. * 属性 写在构造函数下
  18. * 方法 写在原型对象下
  19. *
  20. */
  21. function Person(name,age) {
  22. console.log(this);
  23. this.name = name;
  24. this.age = age;
  25. }
  26. Person.prototype.eat = function() {
  27. console.log("吃粽子")
  28. }
  29. Person.prototype.drink = function() {
  30. console.log("喝甜水")
  31. }
  32. var p1 = new Person('Lucy',20);
  33. console.log(p1.name,p1.age);
  34. p1.eat();
  35. p1.drink();
  36. p1.name = '哈哈';
  37. console.log(p1);
  38. /**
  39. * 原型
  40. * 1.构造函数中自带了constructor(构造器)和prototype(原型对象/显式的方法)
  41. * 2.constructor 指向的是 prototype 的构造函数
  42. * 3.__proto__和prototype是等价的
  43. */
  44. /**
  45. * 原型链:
  46. * 访问对象属性时 先上对象本身的属性去找
  47. * 通过__proto__(原型自带的一个隐式方法)去构造函数上找
  48. * 若还未找到 则在原型对象prototype上去找 若在为找到 则返回null
  49. */
  50. </script>
  51. </body>
  52. </html>