变量提升&函数提升

示例 1:变量提升

原始代码

复制代码
console.log(x); // 输出: undefined
var x = 5;
console.log(x); // 输出: 5

提升后的代码(理解为):

复制代码
var x; // 变量声明被提升
console.log(x); // 输出: undefined
x = 5; // 赋值
console.log(x); // 输出: 5

解析

  1. var x; 这条声明被提升到顶部。
  2. 第一个 console.log(x); 输出 undefined,因为 x 尚未被赋值。
  3. 然后 x = 5; 被执行,给 x 赋值为 5
  4. 第二个 console.log(x); 输出 5

示例 2:函数提升

原始代码

复制代码
greet(); // 输出: Hello!

function greet() {
    console.log("Hello!");
}

提升后的代码(理解为):

复制代码
function greet() {
    console.log("Hello!");
}

greet(); // 输出: Hello!

解析

  1. function greet() { ... } 这个函数声明会被提升到函数作用域的顶部。
  2. 函数可以在声明之前被调用,因此 greet(); 调用成功,并输出 "Hello!"。

示例 3:函数表达式的提升

原始代码

复制代码
console.log(func); // 输出: undefined
var func = function() {
    console.log("This is a function expression");
}
func(); // 运行时会抛出错误: TypeError: func is not a function

提升后的代码(理解为):

复制代码
var func; // 变量声明被提升
console.log(func); // 输出: undefined
func = function() {
    console.log("This is a function expression");
}

func(); // TypeError: func is not a function

解析

  1. var func; 声明被提升,func 变量的值在此时是 undefined
  2. 第一个 console.log(func); 输出 undefined
  3. func 被赋值为一个函数。这时如果我们在没有调用前进行调用会因为 funcundefined 而抛出错误。
  4. 如果这里再调用 func();,会导致一个 TypeError,因为 func 没有赋值为实际的函数。

示例 4:命名函数表达式的提升

原始代码

复制代码
console.log(myFunction); // 输出: undefined
myFunction(); // TypeError: myFunction is not a function

var myFunction = function hey() {
    console.log("Hello, world!");
};

myFunction(); // 输出: "Hello, world!"

提升后的代码(理解为):

复制代码
var myFunction; // 变量声明被提升

console.log(myFunction); // 输出: undefined
myFunction(); // TypeError: myFunction is not a function

myFunction = function hey() { // 赋值
    console.log("Hello, world!");
};

myFunction(); // 输出: "Hello, world!"

解析

  1. var myFunction; 声明被提升,因此在第一次使用时,myFunction 是已声明的,但尚未赋值,因此其值为 undefined
  2. 当到达 myFunction(); 这一行时,myFunction 仍然是 undefined,因此会引发 TypeError,表示 myFunction 不是一个函数。
  3. myFunction = function hey() { ... } 这行之后,myFunction 被赋予了一个函数引用,因此再调用 myFunction(); 时会输出 "Hello, world!"。

总结

  • 变量提升:只提升声明,不提升赋值。
  • 函数提升:提升整个函数声明,允许在函数声明之前调用。
  • 函数表达式 :提升变量声明,赋值不会被提升,因此会导致 undefined
相关推荐
JinSo18 小时前
我的2025年度总结:EasyEditor
前端·程序员
喝拿铁写前端1 天前
前端开发者使用 AI 的能力层级——从表面使用到工程化能力的真正分水岭
前端·人工智能·程序员
wuhen_n1 天前
LeetCode -- 15. 三数之和(中等)
前端·javascript·算法·leetcode
七月shi人1 天前
AI浪潮下,前端路在何方
前端·人工智能·ai编程
非凡ghost1 天前
MusicPlayer2(本地音乐播放器)
前端·windows·学习·软件需求
脾气有点小暴1 天前
scroll-view分页加载
前端·javascript·uni-app
beckyye1 天前
ant design vue Table根据数据合并单元格
前端·antd
布列瑟农的星空1 天前
还在手动翻译国际化词条?AST解析+AI翻译实现一键替换
前端·后端·ai编程
土豆12501 天前
Rust 错误处理完全指南:从入门到精通
前端·rust·编程语言