箭头函数语法更简洁且继承外层this,适合回调;传统函数有独立this和arguments,可用于构造对象。

箭头函数是ES6引入的一种更简洁的函数书写方式,它与传统函数在语法、this指向、使用场景等方面存在显著差异。理解这些区别有助于写出更清晰、不易出错的JavaScript代码。
1. 语法上的简洁性
箭头函数最大的特点是语法更简洁,适合写简单的回调函数。
传统函数写法:
const add = function(a, b) {return a + b;
};
箭头函数写法:
const add = (a, b) => a + b;当参数只有一个时,括号可省略:
const square = x => x * x;无参数时需写空括号:
const getName = () => 'Alice';2. this 指向的不同
这是箭头函数和传统函数最核心的区别。
传统函数有自己的 this 上下文,它的值取决于函数如何被调用。而箭头函数没有自己的this,它会继承外层作用域的 this 值。
示例:在对象方法中使用 setTimeout
const user = {name: 'Bob',
sayHi: function() {
setTimeout(function() {
console.log('Hello, ' + this.name); // undefined
}, 100);
}
};
user.sayHi();
上面例子中,内部函数的 this 不指向 user。解决办法之一是缓存 this:
sayHi: function() {const self = this;
setTimeout(function() {
console.log('Hello, ' + self.name); // Bob
}, 100);
}
使用箭头函数则更自然:
setTimeout(() => {
console.log('Hello, ' + this.name); // Bob
}, 100);
}
因为箭头函数的 this 继承自 sayHi 方法的执行上下文。
3. 不绑定 arguments 对象
传统函数内可以使用 arguments 类数组对象获取所有传入参数。
function logArgs() {console.log(arguments);
}
logArgs(1, 2, 3); // [1, 2, 3]
箭头函数中访问 arguments 会报错或引用外层的 arguments(如果存在)。
正确做法是使用 ES6 的剩余参数(...args):
const logArgs = (...args) => {console.log(args); // [1, 2, 3]
};
logArgs(1, 2, 3);
4. 不能作为构造函数
箭头函数不能用 new 调用,因为它没有 [[Construct]] 方法。
const Person = (name) => this.name = name;const p = new Person('Tom'); // 报错:Person is not a constructor
传统函数可以正常用于构造对象:
function Person(name) {this.name = name;
}
const p = new Person('Tom');
5. 没有 prototype 属性
由于箭头函数不能作为构造器,它也没有 prototype 属性。
const fn1 = () => {};console.log(fn1.prototype); // undefined
传统函数则有:
function fn2() {}console.log(fn2.prototype); // {constructor: fn2}
基本上就这些关键区别。箭头函数适合写简单逻辑、回调函数,尤其是需要保持 this 上下文的场景;传统函数更适合定义方法、构造函数或需要 arguments 的复杂逻辑。根据实际需求选择即可。不复杂但容易忽略。










