18_this指向.html 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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. </head>
  8. <body>
  9. <button id="btn">点击我</button>
  10. <script>
  11. // this 指向问题 this一般指向调用它的对象
  12. // 如果有事件绑定,this指向事件绑定的对象
  13. let btn = document.getElementById("btn");
  14. btn.onclick = function(){
  15. // function bar(){
  16. // console.log(this);
  17. // }
  18. // bar();
  19. let bar = () => {
  20. console.log(this);
  21. }
  22. bar();
  23. console.log(this);
  24. }
  25. // 普通函数中 this指向window对象 默认为winow调用
  26. // function foo(){
  27. // console.log(this);
  28. // // 内部函数中 this指向window对象
  29. // function bar(){
  30. // console.log(this);
  31. // }
  32. // bar();
  33. // }
  34. // foo();
  35. // let obj = {
  36. // name:"张三",
  37. // age:18,
  38. // sex:"男",
  39. // sayName(){
  40. // console.log(this);
  41. // // function bar(){
  42. // // console.log(this);
  43. // // }
  44. // // bar();
  45. // // 箭头函数中 this指向为当前所在作用域的this (箭头函数中没有this)
  46. // let bar = () => {
  47. // console.log(this);
  48. // }
  49. // bar();
  50. // }
  51. // }
  52. // obj.sayName();
  53. </script>
  54. </body>
  55. </html>