javascript - 为什么局部作用域不引用全局变量?

标签 javascript variables scope global local

我的本​​地范围有问题。第二个console.log不显示“a”值,但显示未定义。为什么这样?

"use strict"

console.log(a); //undefined 
var a = "a";
function b(){
  console.log(a); // why is undefined here? 
  var a = "a1";
  console.log(a); // here is "a1"
}
b();

最佳答案

JS 将处理您的代码,如下所示:

"use strict"

var a; // undefined 
console.log(a); //undefined 

a = "a";

function b(){
  var a; // undefined

  console.log(a); // all is clear, LOCAL variable a is undefined. 

  a = "a1";
  console.log(a); // here is "a1"
}

b();

了解有关吊装的更多信息 here .

您还可以阅读 Function declaration hoisting ,这也是 JavaScript 基础知识的重要组成部分。

关于javascript - 为什么局部作用域不引用全局变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36859932/

相关文章:

javascript - 在 map 上的两个投影点之间绘制线 - 不显示线 - D3.js

javascript - 在.html Javascript循环中使用Django View 中的字典(SyntaxError-意外 token : &#x27)

ios - 在 Objective-C 中调用 setter

c++ - 使用来自不同文件的命名空间成员

javascript - 对象创建期间的“this”上下文

php - PHP函数作用域

javascript - 如何获取使用地理定位创建的动态内容并在另一个 div 中使用它?

javascript - 无法将变量设置为外部函数

php - 用换行符分解字符串

javascript - React HTMLAudioElement 不会暂停