变量提升&函数提升

示例 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
相关推荐
qianmoQ16 分钟前
第五章:工程化实践 - 第三节 - Tailwind CSS 大型项目最佳实践
前端·css
C#Thread22 分钟前
C#上位机--流程控制(IF语句)
开发语言·javascript·ecmascript
尚学教辅学习资料26 分钟前
基于SpringBoot+vue+uniapp的智慧旅游小程序+LW示例参考
vue.js·spring boot·uni-app·旅游
椰果uu32 分钟前
前端八股万文总结——JS+ES6
前端·javascript·es6
微wx笑1 小时前
chrome扩展程序如何实现国际化
前端·chrome
~废弃回忆 �༄1 小时前
CSS中伪类选择器
前端·javascript·css·css中伪类选择器
CUIYD_19891 小时前
Chrome 浏览器(版本号49之后)‌解决跨域问题
前端·chrome
IT、木易1 小时前
跟着AI学vue第五章
前端·javascript·vue.js
薛定谔的猫-菜鸟程序员1 小时前
Vue 2全屏滚动动画实战:结合fullpage-vue与animate.css打造炫酷H5页面
前端·css·vue.js
春天姐姐2 小时前
vue3项目开发总结
前端·vue.js·git