js 箭头实现
箭头函数的语法
箭头函数(Arrow Function)是ES6引入的一种简化函数定义的语法,使用 => 符号。基本语法如下:
const func = (param1, param2) => {
// 函数体
return value;
};
单参数简写
如果只有一个参数,可以省略括号:
const square = x => x * x;
无参数函数
没有参数时,必须保留空括号:
const greet = () => console.log("Hello");
隐式返回
当函数体只有单行表达式时,可省略 {} 和 return,自动返回表达式结果:
const double = x => x * 2;
多行函数体
需要显式使用 {} 和 return:
const sum = (a, b) => {
const result = a + b;
return result;
};
返回对象字面量
直接返回对象时需用 () 包裹,避免与函数体的 {} 冲突:
const getObj = () => ({ name: "Alice", age: 25 });
箭头函数的特性
- 没有自己的
this:继承外层作用域的this,适合回调函数(如事件处理器)。 - 不能作为构造函数:无法通过
new调用。 - 没有
arguments对象:需使用剩余参数(...args)替代。
常见用例
数组方法回调:
const numbers = [1, 2, 3];
const squared = numbers.map(n => n * n); // [1, 4, 9]
事件监听器:
button.addEventListener("click", () => {
console.log("Button clicked");
});
类方法中的问题:
箭头函数不适合用于需要动态 this 的类方法,此时应使用普通函数:

class Person {
constructor(name) {
this.name = name;
}
// 错误示例:箭头函数会绑定到实例创建时的 this
sayHi = () => console.log(`Hi, I'm ${this.name}`);
}






