3.this指向.html 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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-color: #f00;
  12. }
  13. </style>
  14. </head>
  15. <body>
  16. <div id="box"></div>
  17. <script>
  18. const box = document.getElementById("box");
  19. // 1.点击事件 指向当前对象
  20. // box.onclick = function () {
  21. // console.log(this);
  22. // }
  23. // // 2.定时器 指向window
  24. // setInterval(() => {
  25. // console.log(this);
  26. // }, 2000);
  27. // 3.对象中 普通函数方法 this指向当前对象
  28. // 3.对象中 箭头函数方法 this指向window
  29. // let obj = {
  30. // name: "张三",
  31. // age: 18,
  32. // say: () => {
  33. // console.log(this);
  34. // }
  35. // }
  36. // obj.say();
  37. // 4.普通函数 this指向window
  38. function fn() {
  39. console.log(this);
  40. }
  41. fn()
  42. </script>
  43. </body>
  44. </html>