javascript - 在具有相同变量名的函数内部提升
问题描述
所以我以为我理解了 JavaScript 中的提升,直到我看到这样的东西:
function hoist(a) {
console.log(a);
var a = 10;
}
hoist(5);
上面的代码输出5
,不是undefined
!根据我的理解,函数对解释器来说是这样的:
function hoist(a) {
var a; // This should overshadow the parameter 'a' and 'undefined' should be assigned to it
console.log(a); // so this should print undefined
a = 10; // now a is assigned 10
}
那么这里发生了什么?
解决方案
如果 var 被调用,你会是对的b
,但 vara
已经存在。重新声明一个已经存在的 javascript 变量不会做任何事情。它不会将值更改为未定义。尝试一下。
function hoist(a) {
var a; // no op, does not change a to undefined.
console.log(a);
a = 10;
}
hoist(18);
推荐阅读
- regex - 在带引号的字符串 csv 文件中有多个双引号
- javascript - 当我运行此代码时,为什么控制台会在循环之前返回第一个随机数?
- powerbi - Power BI - 在矩阵总计上使用切片器
- javascript - 如何在three.js中使用Vector3创建box3?
- arrays - 如何将变量用作数组中的选项?
- css - 创建一个 Angular 可调整大小的水平卡片
- ruby-on-rails - AdapterNotSpecified 使用 ClearDB for MySQL 将 Rails 应用程序部署到 Heroku
- jquery - 如何在jquery中选中复选框上的父节点的ID?
- java - 关于 Eclipse Java 登录处理功能
- wordpress - 网站在删除后仍显示旧首页