18_this指向问题.html 1016 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>Document</title>
  8. <style>
  9. #div1 {
  10. width: 200px;
  11. height: 200px;
  12. background: red;
  13. }
  14. </style>
  15. </head>
  16. <body>
  17. <div id="div1"></div>
  18. <script>
  19. var div1 = document.getElementById('div1')
  20. //1.当前对象引用中,谁的事件 this就是谁
  21. div1.onclick = function () {
  22. console.log(this)
  23. }
  24. //2.在定时器里面 this永远指向window
  25. // var timer = setInterval(function(){
  26. // console.log(this)
  27. // },1000)
  28. //3.对象下面 this指向对象本身
  29. // var person = {
  30. // name: 'zs',
  31. // age: 20,
  32. // eat: function(){
  33. // console.log(this)
  34. // }
  35. // }
  36. // person.eat()
  37. //4.函数内 this指向window
  38. function myFun(){
  39. console.log(this)
  40. }
  41. myFun()
  42. </script>
  43. </body>
  44. </html>