18_this指向.html 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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: pink;
  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. // }, 2000)
  28. // div1.onclick = function () {
  29. // var timer = setInterval(function () {
  30. // console.log(this)
  31. // }, 2000)
  32. // }
  33. //3.在对象下面 this指向对象本身
  34. // var person = {
  35. // name: 'zs',
  36. // age: 20,
  37. // eat: function(){
  38. // console.log(this)
  39. // }
  40. // }
  41. // person.eat()
  42. //4.在函数内 this指向window
  43. // function xx(){
  44. // console.log(this)
  45. // }
  46. // xx()
  47. div1.onclick = function(){
  48. console.log(this,'a')
  49. var timer = setInterval(function(){
  50. console.log(this,'b')
  51. },2000)
  52. abc()
  53. }
  54. var abc = function(){
  55. console.log(this,'c')
  56. }
  57. console.log(this,'d')
  58. /*
  59. div a d window
  60. window b a div
  61. window c c window
  62. window d b window
  63. */
  64. </script>
  65. </body>
  66. </html>