当前位置:   article > 正文

箭头函数的用法_箭头函数的套用

箭头函数的套用

箭头函数是什么

1. 认识箭头函数

2. 箭头函数的结构

  • const/let 函数名 = 参数 => 函数体。

3. 如何将一般函数改写成箭头函数

  1. // 3.如何将一般函数改写成箭头函数
  2. // 一般函数形式
  3. function add() {}
  4. // 箭头函数形式
  5. const add = () => {};

箭头函数的注意事项

1. 单个参数

2. 单行函数体

3. 单行对象

this 指向

1. 全局作用域中的 this 指向

2. 一般函数(非箭头函数)中的 this 指向

  • 只有在函数调用的时候 this 指向才确定,不调用的时候,不知道指向谁。
  • this 指向和函数在哪儿调用没关系,只和谁在调用有关。
  • 没有具体调用对象的话,this 指向 undefined,在非严格模式下,转向 window,默认是非严格模式。

3. 箭头函数中的 this 指向

  • 箭头函数没有自己的 this。

不适用箭头函数的场景

1. 作为构造函数

2. 需要 this 指向调用对象的时候

  •  一般函数:

  •  箭头函数:

3. 需要使用 arguments 的时候

箭头函数的应用

  • 点击按钮开始计时。

  • 使用一般函数需要使用that=this,对当前的this对象进行保存。
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <title>模板字符串的应用</title>
  6. <style>
  7. body {
  8. padding: 50px 0 0 250px;
  9. font-size: 30px;
  10. }
  11. #btn {
  12. width: 100px;
  13. height: 100px;
  14. margin-right: 20px;
  15. font-size: 30px;
  16. cursor: pointer;
  17. }
  18. </style>
  19. </head>
  20. <body>
  21. <button id="btn">开始</button>
  22. <span id="result">0</span>
  23. <script>
  24. const btn = document.getElementById('btn');
  25. const result = document.getElementById('result');
  26. const timer = {
  27. time: 0,
  28. start: function () {
  29. let that = this;
  30. btn.addEventListener(
  31. 'click',
  32. function () {
  33. setInterval(function () {
  34. that.time++;
  35. result.innerHTML = that.time;
  36. }, 1000);
  37. },
  38. false
  39. );
  40. }
  41. };
  42. timer.start();
  43. </script>
  44. </body>
  45. </html>
  • 使用箭头函数,由于箭头函数没有this会自动向外层逐级查找,这样可以剩去that=this操作。
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <title>模板字符串的应用</title>
  6. <style>
  7. body {
  8. padding: 50px 0 0 250px;
  9. font-size: 30px;
  10. }
  11. #btn {
  12. width: 100px;
  13. height: 100px;
  14. margin-right: 20px;
  15. font-size: 30px;
  16. cursor: pointer;
  17. }
  18. </style>
  19. </head>
  20. <body>
  21. <button id="btn">开始</button>
  22. <span id="result">0</span>
  23. <script>
  24. const btn = document.getElementById('btn');
  25. const result = document.getElementById('result');
  26. const timer = {
  27. time: 0,
  28. start: function () {
  29. btn.addEventListener(
  30. 'click',
  31. () => {
  32. setInterval(() => {
  33. this.time++;
  34. result.innerHTML = this.time;
  35. }, 1000);
  36. },
  37. false
  38. );
  39. }
  40. };
  41. timer.start();
  42. </script>
  43. </body>
  44. </html>
本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/115872
推荐阅读
相关标签
  

闽ICP备14008679号