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

箭头函数是ES6版函数声明/表达式?是否为普通JS函数或匿名函数的替代?

箭头函数的本质与变量提升问题解答

Great question! Let's unpack this clearly, starting with what arrow functions actually are, then diving into why only your normal function works when called before its declaration.

1. 箭头函数到底是普通函数的ES6版本?还是匿名函数的ES6版本?

Neither is accurate—let's break this down:

  • Arrow functions are not "ES6 versions of regular functions": Regular functions (declared with function) have their own this binding, access to the arguments object, and a prototype property. Arrow functions lack all three of these; instead, they inherit this lexically from their surrounding scope. This makes them fundamentally different from regular functions, not just a "newer update".
  • Arrow functions aren't just "ES6 anonymous functions": Anonymous functions (unnamed functions like function() {}) existed long before ES6. While arrow functions are often used anonymously (e.g., as callbacks), you can also assign them to variables to create a named reference (like const arrowFun = () => {}). The key distinction isn't anonymity—it's the unique lexical scoping behavior that makes arrow functions useful for specific scenarios (like preserving this in callbacks).

2. 为什么只有普通函数能在声明前调用?

This all boils down to hoisting—how JavaScript moves declarations to the top of their scope during execution:

  • Regular function declarations (function oldOne() {}): These are fully hoisted. JavaScript moves the entire function definition to the top of the scope, so calling oldOne() before its written declaration works perfectly—JS already knows about the function.
  • Anonymous functions assigned to variables (var anonym = function() {}): Only the variable declaration (var anonym) is hoisted, not the function assignment. Before the line where you assign the function, anonym is undefined. Calling undefined() will throw a TypeError.
  • Arrow functions assigned to variables (var arrowFun = () => {}): This works exactly like the anonymous function case. The var arrowFun declaration is hoisted, but the arrow function assignment isn't. So calling arrowFun() before its assignment line will also throw a TypeError.

Let’s test this with your code snippet (adding calls before declarations to see the behavior):

// 尝试在声明前调用各函数
oldOne(); // 正常输出 "Hello World..!"
anonym(); // 抛出 TypeError: anonym is not a function
arrowFun(); // 抛出 TypeError: arrowFun is not a function

// Normal Function
function oldOne() {
  console.log("Hello World..!");
}
// Anonymous function
var anonym = function(){
  console.log("Hello World..!");
}
// ES6
var arrowFun = () => {
  console.log("Hello World..!");
}

内容的提问来源于stack exchange,提问作者Thidasa Pankaja

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 12:21:32