一、概述

1.1 定义一个简单的箭头函数:

  1. x => x * x

等价于:

  1. function (x) {
  2. return x * x;
  3. }

1.2 不同参数的箭头函数

  1. // 没有参数
  2. var f1 = () => 3.14;
  3. console.log(f1()); // output: 3.14
  4. // 一个参数
  5. var f2 = x => x * x;
  6. console.log(f2(5)); // output: 25
  7. // 两个参数
  8. var f3 = (x, y) => x * x + y * y;
  9. console.log(f3(6, 8)); // output: 100
  10. // 可变参数
  11. var f4 = (x, y, ...rest) => {
  12. var i, sum = x + y;
  13. for (i = 0; i < rest.length; i++) {
  14. sum += rest[i];
  15. }
  16. return sum;
  17. }
  18. console.log("sum = " + f4(1, 2, 3, 4, 5)); // output: sum = 15
  19. // 返回对象字面量表达式,细节外层大括号变为小括号,然后对象用大括号表示
  20. var f5 = x => ({ foo: x+2 });
  21. console.log(f5(20)); // output: {"foo": 22}

二、箭头函数 this 绑定问题

2.1 this 绑定有误

  1. var obj = {
  2. birth: 1997,
  3. getAge: function () {
  4. var b = this.birth; // 这个 this 指向 obj 所以获取到 1997
  5. var fn = function () {
  6. return new Date().getFullYear() - this.birth; // 这个 this 指向 window, 获取不到值
  7. };
  8. return fn();
  9. }
  10. };
  11. // fn 函数中 this 指向 window
  12. console.log(obj.getAge()); // output: NaN

普通函数 fnthis会指向 window,因此获取不到我们想要的结果。

2.2 通过引入一个 that 变量保存 this 值

  1. var obj = {
  2. birth: 1997,
  3. getAge: function () {
  4. var b = this.birth; // 这个 this 指向 obj 所以获取到 1997
  5. var that = this; // 用 that 保存 this 的值
  6. var fn = function () {
  7. return new Date().getFullYear() - that.birth; // 这个 that 指向 obj,可以获取到值
  8. };
  9. return fn();
  10. }
  11. };
  12. console.log(obj.getAge()); // output: 25

2.3 通过箭头函数

  1. var obj = {
  2. birth: 1997,
  3. getAge: function () {
  4. var b = this.birth; // 1997
  5. var fn = () => new Date().getFullYear() - this.birth; // this 指向 obj 对象
  6. return fn();
  7. }
  8. };
  9. console.log(obj.getAge()); // 25

箭头函数不会创建自己的 this, 它只会从自己的作用域链的上一层继承 this,这个例子中就是 obj 对象。