ES6从入门到精通:箭头函数
箭头函数的基本语法
ES6 引入了箭头函数(Arrow Functions),提供了一种更简洁的函数写法。箭头函数使用 =>
语法定义,省略了 function
关键字。
// 传统函数
function add(a, b) {return a + b;
}// 箭头函数
const add = (a, b) => a + b;
箭头函数可以省略大括号 {}
和 return
关键字(仅适用于单行表达式)。如果函数体有多行,仍需使用大括号和 return
。
const multiply = (a, b) => {const result = a * b;return result;
};
箭头函数的参数
箭头函数对参数的处理非常灵活:
- 如果只有一个参数,可以省略括号
()
。 - 如果没有参数或多个参数,必须保留括号。
// 单参数
const square = x => x * x;// 无参数
const greet = () => console.log("Hello!");// 多参数
const sum = (a, b, c) => a + b + c;
箭头函数与 this
绑定
箭头函数与传统函数的最大区别在于 this
的绑定行为。箭头函数没有自己的 this
,而是继承外层作用域的 this
。
const person = {name: "Alice",traditionalGreet: function() {console.log("Traditional:", this.name);},arrowGreet: () => {console.log("Arrow:", this.name); // `this` 指向全局对象或 undefined(严格模式)}
};person.traditionalGreet(); // 输出 "Traditional: Alice"
person.arrowGreet(); // 输出 "Arrow: undefined"(非严格模式下可能指向全局对象)
由于箭头函数的 this
是相对静态的(父元素this),它非常适合用于回调函数(如事件处理、定时器),避免 this
丢失的问题。
const button = document.getElementById("myButton");
button.addEventListener("click", () => {console.log(this); // 继承外层 `this`(如全局作用域)
});// 对比传统函数
button.addEventListener("click", function() {console.log(this); // 指向按钮元素
});
箭头函数的限制
箭头函数不能用作构造函数,不能通过 new
调用(区分二义性)。
const Foo = () => {};
new Foo(); // TypeError: Foo is not a constructor
箭头函数也没有 arguments
对象,但可以使用剩余参数(Rest Parameters)替代。
const showArgs = (...args) => console.log(args);
showArgs(1, 2, 3); // 输出 [1, 2, 3]
箭头函数的适用场景
-
简化回调函数:
const numbers = [1, 2, 3]; const doubled = numbers.map(n => n * 2);
-
避免
this
绑定问题:const timer = {seconds: 10,start() {setInterval(() => {console.log(this.seconds--); // 正确指向 `timer` 对象}, 1000);} };
-
单行表达式函数:
const isEven = num => num % 2 === 0;
注意事项
- 箭头函数不适合用于对象方法(需访问对象自身的
this
时)。 - 避免在需要动态
this
的场景(如 DOM 事件回调)中使用箭头函数。 - 箭头函数不能通过
bind
、call
或apply
修改this
。