1、实例

  1. // 1.箭头函数例子
  2. function add(a, b) {
  3. return a + b;
  4. }
  5. // 1.使用箭头函数表达上面的函数
  6. let add1 = (a, b) => {
  7. return a + b;
  8. }
  9. // 2.简写方式: 函数体只有一行时
  10. let add2 = (a, b) => a + b;
  11. // 3.参数只有一个,小括号可以省略
  12. function squart(num) {
  13. return num * num;
  14. }
  15. // 简写
  16. let squart2 = num => num * num;

2、箭头函数的使用场景

  1. // 1.2 箭头函数常见使用场景
  2. // 1. 回调函数
  3. const list = [1, 2, 3, 4, 5, 6];
  4. list.forEach(function(item, index) {
  5. // todo
  6. });
  7. list.forEach((item, index) => {
  8. // todo
  9. });
  10. list.forEach(item => {
  11. // todo
  12. });
  13. // 2.setTimout
  14. setTimeout(() => {
  15. // todo
  16. }, 1000)
  17. // 3.promise
  18. let promiseObj = new Promise((resolve, reject) => {
  19. // todo
  20. })
  21. promiseObj.then(res => {
  22. // todo
  23. }).catch(err => {
  24. // todo
  25. });

3、箭头函数的this指向

  1. // 箭头函数this的指向
  2. let obj = {
  3. getList() {
  4. console.log('this的指向', this);//obj
  5. setTimeout(()=> {
  6. console.log('setTimout', this);//window
  7. }, 1000);
  8. }
  9. }
  10. obj.getList();