9.箭头函数.html 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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: 300px;
  10. height: 300px;
  11. background: #0f0;
  12. }
  13. </style>
  14. </head>
  15. <body>
  16. <!--
  17. 箭头函数:()=>{代码块...}
  18. 特点:
  19. 1.普通函数中this指向window 箭头函数this指向的是上级作用域
  20. 2.箭头函数中没有arguments
  21. 3.普通函数中this指向可以修改 箭头函数中this指向不能修改
  22. 4.箭头函数中代码块中只有一条语句 可以省略代码块
  23. 5.箭头函数不可以使用new
  24. -->
  25. <div id="box"></div>
  26. <button id="btn">点击</button>
  27. <script>
  28. var box = document.getElementById("box");
  29. var btn = document.getElementById("btn");
  30. // 普通函数
  31. // function fn1() {
  32. // }
  33. // fn1()
  34. // 匿名函数
  35. // let aa = function() {
  36. // }
  37. // aa();
  38. // 立即执行函数
  39. // (function() {
  40. // console.log("你好")
  41. // })()
  42. let obj = {
  43. name:"图图"
  44. }
  45. function fn1() {
  46. console.log(this.name);
  47. console.log(arguments);
  48. }
  49. console.log(new fn1(),'普通')
  50. // fn1.call(obj);
  51. // 箭头函数
  52. let fn2 = () => console.log(this.name,'箭头函数');
  53. // console.log("好好好", ...rest);
  54. ;
  55. // fn2.call(obj);
  56. // fn2('你好');
  57. console.log(new fn2(),'箭头')
  58. btn.onclick = function () {
  59. console.log(this);
  60. setTimeout(function () {
  61. let fn3 = () => {
  62. console.log("我好", this);
  63. };
  64. fn3();
  65. }, 2000);
  66. };
  67. </script>
  68. </body>
  69. </html>