26.原型、原型链及构造函数.html 1.8 KB

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