9.原型和原型链.html 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. // function fn() {
  12. // console.log(this);
  13. // }
  14. // fn();
  15. // // 箭头函数
  16. // const fn1 = () => {
  17. // }
  18. // // 匿名函数
  19. // let xxx = function () {
  20. // }
  21. // // 立即执行函数
  22. // (function () {
  23. // })()
  24. // function fn1() {
  25. // console.log(this);
  26. // return 1;
  27. // }
  28. // console.log(fn1())
  29. /**
  30. * 构造函数
  31. * 1.首字母大写
  32. * 2.通过new关键字调用
  33. * 3.构造函数中this指向当前实例对象
  34. * 4.不用return返回值
  35. *
  36. * 属性写在构造函数中
  37. * 方法写在原型中
  38. */
  39. function Fn2() {
  40. this.name = '图图';
  41. this.age = 3;
  42. console.log(this, 'this');
  43. }
  44. Fn2.prototype.say = function () {
  45. console.log('我叫' + this.name);
  46. }
  47. let aa = new Fn2();
  48. console.log(aa);
  49. aa.say();
  50. /**
  51. * 原型:
  52. * 1.所有的构造函数都自带了一个prototype(显性)属性,该属性指向的就是当前构造函数的原型
  53. * 2.所有构造函数的原型上,自带了constructor(隐性)属性,该属性指向的就是当前构造函数
  54. * 3.构造函数可以通过new进行实例化 产生该构造函数的实例化对象
  55. * 4.实例化对象 可以通过_proto_属性访问到该构造函数的原型对象
  56. */
  57. function Person() {};
  58. var person = new Person();
  59. console.log(person.__proto__ == Person.prototype);
  60. console.log(Person.prototype.constructor == Person);
  61. console.log(Object.getPrototypeOf(person) === Person.prototype);
  62. /**
  63. * 原型链:
  64. * 1.访问对象的属性或方法时 现在实例化对象上查找
  65. * 2.如果实例化对象上没有找到 通过_proto_属性访问到的原型对象上查找
  66. * 3.如果原型对象上没有找到 则去原型对象的原型上查找 找到则返回 找不到返回undefined
  67. * 4.原型链的终点 null
  68. */
  69. </script>
  70. </body>
  71. </html>