24.this指向问题.html 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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: #f00;
  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); //box
  22. }
  23. // 2.倒计时 this指向window
  24. box.onclick = function() {
  25. setInterval(function() {
  26. console.log(this); //
  27. },1000)
  28. }
  29. // 3.对象中的this 指向当前对象
  30. var obj = {
  31. name:"Lucy",
  32. age: 18,
  33. address:function() {
  34. console.log(this);
  35. }
  36. }
  37. obj.address()
  38. //4.函数中的this 指向window
  39. function fn1() {
  40. console.log(this);
  41. }
  42. fn1();
  43. </script>
  44. </body>
  45. </html>