【JavaScript】箭头函数与普通函数的区别

ES6 引入的箭头函数写法更简洁,但它不只是语法糖:箭头函数和普通函数在 this、arguments、构造能力上有本质区别,选错会直接引发 bug。

1. 语法形式

// 普通函数
function add(a, b) {
    return a + b;
}

// 箭头函数:单表达式可省略 return 和花括号
const add2 = (a, b) => a + b;

// 只有一个参数时可省略括号
const double = n => n * 2;

// 返回对象字面量需要加括号
const make = (name, age) => ({ name, age });

2. this 的指向:最核心的区别

普通函数的 this 由调用方式决定:谁调用指向谁(对象方法调用指向对象,独立调用指向 window/undefined)。箭头函数没有自己的 this,它沿用定义时外层作用域的 this:

const timer = {
    seconds: 0,
    start() {
        // 普通函数:this 是 undefined/window,this.seconds 报错
        // setInterval(function() {
        //     this.seconds++;
        // }, 1000);

        // 箭头函数:沿用 start 方法的 this(即 timer)
        setInterval(() => {
            this.seconds++;
        }, 1000);
    }
};

上面这个例子是箭头函数最经典的用途:回调里需要访问外层 this 时,箭头函数省掉了 const self = this 的老写法。

3. 其他差异

普通函数        箭头函数
this            动态决定      定义时确定
arguments       有            没有(用 rest 参数 ...args)
new 调用        可以          不能用作构造函数
prototype       有            没有
yield           可以成为生成器 不能

箭头函数没有 arguments,需要收集参数时用剩余参数代替:

const sum = (...nums) => nums.reduce((a, b) => a + b, 0);
console.log(sum(1, 2, 3)); // 6

4. 选型建议

需要 this 的场景(对象方法、原型方法、构造函数、事件处理函数里要拿当前元素)用普通函数;回调函数、需要保持外层 this 的场景用箭头函数。把对象字面量方法写成箭头函数是常见错误:

const user = {
    name: "张三",
    // 错误:箭头函数的 this 指向外层,不是 user
    hello: () => console.log(this.name),
    // 正确:普通方法
    hi() { console.log(this.name); }
};
© 版权声明
THE END
喜欢就支持一下吧
点赞11分享
评论 抢沙发

请登录后发表评论

    暂无评论内容