变量提升&函数提升

示例 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 分钟前
vue3 获取选中的el-table行数据
javascript·vue.js·elementui
翻滚吧键盘22 分钟前
vue绑定一个返回对象的计算属性
前端·javascript·vue.js
苦夏木禾26 分钟前
js请求避免缓存的三种方式
开发语言·javascript·缓存
超级土豆粉34 分钟前
Turndown.js: 优雅地将 HTML 转换为 Markdown
开发语言·javascript·html
秃了也弱了。40 分钟前
Chrome谷歌浏览器插件ModHeader,修改请求头,开发神器
前端·chrome
乆夨(jiuze)1 小时前
记录H5内嵌到flutter App的一个问题,引发后面使用fastClick,引发后面input输入框单击无效问题。。。
前端·javascript·vue.js
忧郁的蛋~1 小时前
HTML表格导出为Excel文件的实现方案
前端·html·excel
小彭努力中1 小时前
141.在 Vue 3 中使用 OpenLayers Link 交互:把地图中心点 / 缩放级别 / 旋转角度实时写进 URL,并同步解析显示
前端·javascript·vue.js·交互
然我2 小时前
别再只用 base64!HTML5 的 Blob 才是二进制处理的王者,面试常考
前端·面试·html
NanLing2 小时前
【纯前端推理】纯端侧 AI 对象检测:用浏览器就能跑的深度学习模型
前端