You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React JS中const example = () => {}与function example() {}有什么区别

JavaScript箭头函数与普通函数声明的实际差异
  • this指向逻辑完全不同
    这是两类函数最核心的差异:箭头函数没有独立的this绑定,它的this继承自定义时外层作用域的this,且不会随调用方式的变化而改变。普通函数的this指向调用它的主体,全局调用时非严格模式指向window、严格模式指向undefined,作为对象方法调用时指向该对象。
    示例:
const testObj = {
  content: "测试内容",
  arrowTest: () => console.log(this.content),
  normalTest: function() { console.log(this.content) }
}
testObj.arrowTest() // 输出undefined(this指向外层全局作用域)
testObj.normalTest() // 输出"测试内容"(this指向调用它的testObj)
  • 不能作为构造函数使用
    箭头函数没有构造函数能力,使用new关键字调用箭头函数会直接抛出错误。普通函数可以作为构造函数生成实例对象。
    示例:
const ArrowConstructor = () => {}
new ArrowConstructor() // 运行报错:ArrowConstructor is not a constructor

function NormalConstructor() {}
new NormalConstructor() // 正常生成实例对象
  • 无独立arguments对象
    普通函数内部可以直接访问arguments类数组对象,获取所有传入的参数。箭头函数没有自己的arguments对象,如果需要获取入参,要使用剩余参数语法...args实现。
    示例:
function normalFunc(a, b) {
  console.log(arguments) // 输出[1, 2]的类数组结构
}
normalFunc(1, 2)

const arrowFunc = (a, b) => {
  console.log(arguments) // 运行报错:arguments is not defined
}
arrowFunc(1, 2)

// 箭头函数获取入参的正确写法
const arrowFuncWithArgs = (...args) => {
  console.log(args) // 输出[1, 2]
}
arrowFuncWithArgs(1, 2)
  • 变量提升规则不同
    普通函数声明存在完整的函数提升,在代码执行前就会被提升到作用域顶部,可以在声明位置之前正常调用。箭头函数属于变量赋值表达式,仅会进行变量提升,且使用const声明时存在暂时性死区,无法在赋值之前调用。
    示例:
normalFunc() // 正常输出"普通函数调用成功"
function normalFunc() {
  console.log("普通函数调用成功")
}

arrowFunc() // 运行报错:Cannot access 'arrowFunc' before initialization
const arrowFunc = () => console.log("箭头函数调用成功")
  • 不支持prototype属性与Generator语法
    普通函数拥有prototype原型属性,箭头函数没有该属性。同时箭头函数不能使用yield关键字,无法作为Generator函数使用。

内容的提问来源于stack exchange,提问作者Miguel Matos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 03:06:03