[JavaScript]arrowFunction

98 阅读1分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

arrowFunction

arrow-function-basics

arrow-functions

箭头函数的基础知识

箭头函数对于简单的操作很方便,特别是对于单行的函数。它具体有两种形式:

  1. 不带花括号:(...args) => expression —— 右侧是一个表达式:函数计算表达式并返回其结果。如果只有一个参数,则可以省略括号,例如 n => n*2

    let sum = (a, b) => a + b;
    ​
    /* 这个箭头函数是下面这个函数的更短的版本:
    ​
    let sum = function(a, b) {
      return a + b;
    };
    */
    ​
    alert( sum(1, 2) ); // 3
    
  2. 带花括号:(...args) => { body } —— 花括号允许我们在函数中编写多个语句,但是我们需要显式地 return 来返回一些内容。

let sum = (a, b) => {  // 花括号表示开始一个多行函数
  let result = a + b;
  return result; // 如果我们使用了花括号,那么我们需要一个显式的 “return”
};
​
alert( sum(1, 2) ); // 3

深入理解箭头函数

箭头函数:

  • 没有 this
  • 没有 arguments(看不懂)
  • 不能使用 new 进行调用
  • 没有 super

箭头函数是针对那些没有自己的“上下文”,但在当前上下文中起作用的短代码的。并且箭头函数确实在这种使用场景中大放异彩。

没有 this

/**
 * 这里 forEach 中使用了箭头函数,所以其中的 this.title 其实和外部方法 showList 的完全一样。
 * 那就是:group.title。
 */
let group = {
  title: "Our Group",
  students: [ "John", "Pete", "Alice" ],
​
  showList() {
    this.students.forEach(
      student => console.log(this.title + ': ' + student)
    );
  }
};
​
group.showList();
let group = {
  title: "Our Group",
  students: ["John", "Pete", "Alice"],
​
  showList() {
    this.students.forEach(function(student) {
      // Error: Cannot read property 'title' of undefined
      console.log(this.title + ': ' + student);
    });
  }
};
​
group.showList();

\