变量提升&函数提升

示例 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
相关推荐
前端不太难1 小时前
从 Navigation State 反推架构腐化
前端·架构·react
前端程序猿之路2 小时前
Next.js 入门指南 - 从 Vue 角度的理解
前端·vue.js·语言模型·ai编程·入门·next.js·deepseek
大布布将军2 小时前
⚡️ 深入数据之海:SQL 基础与 ORM 的应用
前端·数据库·经验分享·sql·程序人生·面试·改行学it
川贝枇杷膏cbppg2 小时前
Redis 的 RDB 持久化
前端·redis·bootstrap
D_C_tyu3 小时前
Vue3 + Element Plus | el-table 表格获取排序后的数据
javascript·vue.js·elementui
JIngJaneIL3 小时前
基于java+ vue农产投入线上管理系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot
天外天-亮3 小时前
v-if、v-show、display: none、visibility: hidden区别
前端·javascript·html
jump_jump3 小时前
手写一个 Askama 模板压缩工具
前端·性能优化·rust
hellotutu3 小时前
vue2 从 sessionStorage 手动取 token 后,手动加入到 header
vue.js·token·session·header
be or not to be3 小时前
HTML入门系列:从图片到表单,再到音视频的完整实践
前端·html·音视频