【ES6】箭头函数

146 阅读2分钟

箭头函数

箭头函数的定义

在ES6中,新增了一种用=>定义函数的方法,他的基本语法如下

const add = (a, b) => {
    return a + b;
};

如果函数体只有一行,则可以省略{}return

const add = (a, b) => a + b;

如果函数只有一个参数,甚至连括号也可以省略:

const square = x => x * x;

箭头函数与传统函数的区别

1. 没有 arguments 对象

传统函数具有 arguments 对象,用于访问所有传入函数的参数。而箭头函数没有自己的 arguments 对象,它会继承外部上下文的 arguments

function foo1() {
  console.log(arguments);
}

const foo2 = () => {
  console.log(arguments); // 报错:arguments is not defined
}

foo1(1, 2, 3); // 输出:[1, 2, 3]
foo2(1, 2, 3);       // 报错

2. 没有 prototype 属性

传统函数可以作为构造函数使用,并且具有 prototype 属性,而箭头函数没有这个属性。因此,箭头函数不能被用于创建实例对象。

function Foo() {
  this.value = 42;
}

const foo = new Foo();
console.log(foo.value); // 输出:42

const Foos = () => {
  this.value = 42; // 错误:this is undefined
}

const foo2 = new Foos(); // 错误:Foos is not a constructor

3.上下文绑定不可改

与传统函数不同,箭头函数没有自己的this关键字,它会捕获其所在上下文的this值。这意味着箭头函数内部的this与外部一致,不受函数调用方式的影响

function Counter() {
  this.count = 0;

  // 传统函数表达式
  setInterval(function () {
    this.count++;
    console.log(this.count); // undefined
  }, 1000);

  // 箭头函数
  setInterval(() => {
    this.count++;
    console.log(this.count); // 正确递增
  }, 1000);
}

const counter = new Counter();

箭头函数的常见使用场景

1. 回调函数

在处理回调函数时,箭头函数的简洁语法使得代码更加清晰。传统函数表达式通常需要额外的 function 关键字和大括号,而箭头函数通过省略这些部分,使得代码更为紧凑。

// 传统函数表达式
array.map(function (item) {
  return item + 1;
});

// 箭头函数
array.map(item => item + 1);

在这个例子中,箭头函数作为 map 方法的回调函数,减少了冗余的语法。

2. 定时器和事件处理

在定时器和事件处理中,由于箭头函数不会改变上下文绑定,可以更自然地访问当前对象的属性和方法,而无需通过额外的变量保存上下文。

// 传统函数表达式
setTimeout(function () {
  console.log("Hello, World!");
}, 1000);

// 箭头函数
setTimeout(() => {
  console.log("Hello, World!");
}, 1