26.原型、原型链及构造函数.html 1.7 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. // 普通函数 this指向window
  11. function fn1() {
  12. console.log(this,"1");
  13. }
  14. fn1();
  15. /** 构造函数:初始化对象
  16. * 1.this指向当前对象本身
  17. * 2.首字母大写
  18. * 3.使用时 必须通过new去调用
  19. * */
  20. /**
  21. * 属性 写在构造函数下
  22. * 方法 写在原型下
  23. */
  24. function Person(name,age) {
  25. // console.log(this,'2')
  26. this.name = name;
  27. this.age = age;
  28. console.log(this.name,'name');
  29. console.log(this.age,'age')
  30. Person.prototype.eat = function() {
  31. console.log("该吃午饭了"+this.name);
  32. }
  33. }
  34. // new 实例化
  35. var p1 = new Person("赵家锐",0); // constructor prototype
  36. console.log(p1);
  37. console.log(p1.eat());
  38. //console.log('原型的最终结果',p1.__proto__.__proto__.__proto__); //null
  39. // new Person();
  40. /**
  41. * 原型
  42. * 1.构造函数中自带了constructor(构造器)和prototype(原型对象/显式的方法)
  43. * 2.constructor 指向的是 prototype 的构造函数
  44. * 3.__proto__和prototype是等价的
  45. */
  46. /**
  47. * 原型链:
  48. * 访问对象属性时 先上对象本身的属性去找
  49. * 通过__proto__(原型自带的一个隐式方法)去构造函数上找
  50. * 若还未找到 则在原型对象prototype上去找 若在为找到 则返回null
  51. */
  52. </script>
  53. </body>
  54. </html>