2.this指向.html 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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: 200px;
  10. height: 200px;
  11. background: #00f;
  12. }
  13. </style>
  14. </head>
  15. <body>
  16. <div id="box"></div>
  17. <script>
  18. var box = document.getElementById("box");
  19. // 1.点击事件 this指向点击对象
  20. // box.onclick = function() {
  21. // console.log(this);
  22. // }
  23. // 2.定时器 指向window
  24. // setInterval(function() {
  25. // console.log(this)
  26. // },1000)
  27. // window.onclick = function() {
  28. // setInterval(()=>{
  29. // console.log(this)
  30. // },2000)
  31. // }
  32. // box.onclick = function() {
  33. // setInterval(()=>{
  34. // console.log(this)
  35. // },2000)
  36. // }
  37. // 3.对象中 指向当前对象
  38. // var obj = {
  39. // name:"Lucy",
  40. // age:10,
  41. // address:function() {
  42. // console.log(this);
  43. // }
  44. // }
  45. // obj.address();
  46. // 4.函数中 this执行window
  47. function fn1() {
  48. console.log(this);
  49. }
  50. fn1();
  51. </script>
  52. </body>
  53. </html>