20.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. #box1 {
  9. width: 200px;
  10. height: 200px;
  11. background: #f00;
  12. }
  13. </style>
  14. </head>
  15. <body>
  16. <div id="box1"></div>
  17. <script>
  18. var box1 = document.getElementById("box1");
  19. // 1.点击事件 this指向对象本身
  20. // box1.onclick = function() {
  21. // console.log(this)
  22. // }
  23. // 2.定时器 指向全局window
  24. box1.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>