Javascript:了解奇怪的部分 - 功能范围不按描述工作

Javascript: Understanding the Weird Parts - function scope not working as described

我试过用一百万种方式重写它,但无法弄清楚 Tony Alicea 如何从这段代码中产生结果 1、2、未定义、1:

function b() {
    var myVar;
    console.log(myVar);
}

function a() {
    myVar = 2;
    console.log(myVar)
    b();
}

var myVar = 1;
console.log(myVar);
a();
console.log(myVar);

您可以在 https://www.youtube.com/watch?v=Bv_5Zv5c-Ts&t=74m30s where he executes this and produces 1, 2, undefined, 1. I keep running it and getting 1, 2, undefined, 2. Is there something I'm doing that is causing myVar to exist as 2 in both the global scope and the scope of a()? My code is currently posted at https://testing-mdmitchellnyc.c9.io/hello-world.html 查看代码和视频。

function a() 应该是

function a() {
    var myVar = 2;
    console.log(myVar)
    b();
} 

您现在的方式 function a() 是覆盖全局 myVar 而不是创建其自己的作用域 myVar