函数声明和函数表达式的区别是什么?
请说明函数声明(Function Declaration)和函数表达式(Function Expression)的区别,特别是变量提升方面的差异。
回答
编译有声
函数声明:
function foo() {}
- 整体提升(声明 + 赋值),可在声明前调用
- 必须有函数名
- 块级作用域中(非严格模式)行为不一致
函数表达式:
const bar = function() {};
// 或
const baz = function named() {};
- 仅变量名提升(var)/ TDZ(let/const),函数体不提升
- 可以是匿名或具名
- 具名函数的名称仅在函数体内可访问
关键区别:
foo(); // ✅ 'foo'
function foo() { console.log('foo'); }
bar(); // ❌ TypeError: bar is not a function(var 提升为 undefined)
var bar = function() { console.log('bar'); };
baz(); // ❌ ReferenceError(let TDZ)
let baz = function() { console.log('baz'); };
命名函数表达式的函数名作用域:
const f = function g() { console.log(typeof g); };
f(); // 'function'
console.log(typeof g); // 'undefined'