箭头函数是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 ownthisbinding, access to theargumentsobject, and aprototypeproperty. Arrow functions lack all three of these; instead, they inheritthislexically 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 (likeconst arrowFun = () => {}). The key distinction isn't anonymity—it's the unique lexical scoping behavior that makes arrow functions useful for specific scenarios (like preservingthisin 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 callingoldOne()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,anonymisundefined. Callingundefined()will throw aTypeError. - Arrow functions assigned to variables (
var arrowFun = () => {}): This works exactly like the anonymous function case. Thevar arrowFundeclaration is hoisted, but the arrow function assignment isn't. So callingarrowFun()before its assignment line will also throw aTypeError.
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
相关产品推荐
相关产品推荐

