3.this指向.html 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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. <style>
  8. #box {
  9. width: 300px;
  10. height: 300px;
  11. background: #f00;
  12. }
  13. </style>
  14. </head>
  15. <body>
  16. <div id="box"></div>
  17. <script>
  18. let box = document.getElementById("box");
  19. // 1.点击事件 this指向当前对象
  20. // box.onclick = function() {
  21. // console.log(this);
  22. // }
  23. // 2.定时器 this指向window
  24. // setInterval
  25. // setTimeout(() => {
  26. // console.log(this)
  27. // },3000)
  28. // box.onclick = function () {
  29. // setInterval(function(){
  30. // console.log(this)
  31. // }, 1000)
  32. // }
  33. // 3. 对象中
  34. /**
  35. * this指向
  36. * 普通函数 指向调用本身
  37. * 箭头函数 指向上下文
  38. */
  39. // let obj = {
  40. // aa:1,
  41. // bb:2,
  42. // cc:()=> {
  43. // console.log(this);
  44. // }
  45. // }
  46. // obj.cc();
  47. // 4.普通函数 this指向window
  48. function fn1() {
  49. console.log(this)
  50. }
  51. fn1();
  52. </script>
  53. </body>
  54. </html>