箭头函数与普通函数的核心区别在于this指向、arguments对象和构造函数能力。1. 箭头函数没有自己的this,继承外层作用域的this,适合回调函数;2. 普通函数的this根据调用方式动态绑定;3. 箭头函数无arguments对象,但可用剩余参数替代;4. 箭头函数不能作为构造函数使用,因缺少[[Construct]]方法和prototype属性。

JavaScript中的箭头函数和普通函数,从表面看都是定义函数的方式,但它们在几个关键点上有着本质的区别,最核心的差异体现在它们如何处理
this
arguments
箭头函数和普通函数在行为上的主要差异,我通常会从
this
this
call
apply
bind
this
this
this
举个例子,在一个对象的方法中使用
setTimeout
this
window
setTimeout
this
var self = this
bind
// 普通函数中的this
const obj1 = {
name: '普通函数',
greet: function() {
console.log(`Hello, I'm ${this.name}`); // this指向obj1
setTimeout(function() {
console.log(`Still ${this.name}?`); // this指向window (或undefined在严格模式)
}, 100);
}
};
obj1.greet(); // 输出: Hello, I'm 普通函数; Still undefined? (或Still )
// 箭头函数中的this
const obj2 = {
name: '箭头函数',
greet: function() {
console.log(`Hello, I'm ${this.name}`); // this指向obj2
setTimeout(() => {
console.log(`Still ${this.name}?`); // this捕获外部greet函数的this,指向obj2
}, 100);
}
};
obj2.greet(); // 输出: Hello, I'm 箭头函数; Still 箭头函数?我能用箭头函数创建构造函数吗?
arguments
立即学习“Java免费学习笔记(深入)”;
答案是,你不能用箭头函数作为构造函数。尝试用
new
[[Construct]]
prototype
this
this
至于
arguments
arguments
arguments
arguments
arguments
为了弥补箭头函数没有
arguments
...rest
// 普通函数的arguments
function regularFunc() {
console.log(arguments); // [1, 2, 3]
}
regularFunc(1, 2, 3);
// 箭头函数的arguments
const arrowFunc = (...args) => { // 使用剩余参数替代arguments
console.log(args); // [4, 5, 6]
// console.log(arguments); // ReferenceError: arguments is not defined (在全局作用域下)
// 如果在一个普通函数内部定义,则会引用外部普通函数的arguments
};
arrowFunc(4, 5, 6);什么时候应该选择箭头函数,什么时候又该坚持使用普通函数?
这没有绝对的答案,更多是基于场景和个人习惯的权衡。
我会倾向于在以下情况使用箭头函数:
Array.prototype.map()
filter()
reduce()
forEach()
setTimeout()
Promise
this
bind
that = this
return
this
this
this
而以下情况,我通常会坚持使用普通函数:
this
this
window
undefined
class
arguments
arguments
this
event.currentTarget
this
this
this
最终,选择哪种函数形式,更多是基于对它们行为差异的理解。没有哪一种是“更好”的,只有“更适合”特定场景的。理解这些区别,能帮助你写出更健壮、更易读的JavaScript代码。
以上就是JavaScript箭头函数与普通函数的区别的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号