可变范围问题

Rad*_*adi 5 javascript

由于我是一个JavaScript新手,我开始学习它,但我刚刚开始时卡住了.我正在关注Mozilla教程,我在JavaScript中有可变范围的问题.我有一些代码:

var myvar = "my value";

var zmienna = "string";

(function () {
    alert(myvar);
    alert(zmienna);
})();

(function () {
    alert(myvar); // undefined
    var myvar = "local value";
    alert(zmienna);
})();
Run Code Online (Sandbox Code Playgroud)

在本教程中,我已经读过JavaScript函数块中看不到的JavaScript变量.好吧,前两个警报说正确的值.这很奇怪,因为第三个警报说"未定义",尽管事实上之前的功能块没有任何变化.第四个,再次打印正确的价值.

有谁能解释一下,这里发生了什么?我会很高兴,因为教程没有更多关于这一点.

Que*_*tin 9

使用var是悬挂的.

由于你有var myvar函数内部,有一个本地范围myvar.由于您在发出警报后为其指定了值,因此就是undefined在您发出警报时.


use*_*716 1

“我读到 JavaScript 变量在功能块中不可见。”

这不太正确。它们可以从嵌套函数中获得。

嵌套函数创建作用域链。在另一个函数内部创建的函数可以访问它自己的变量以及嵌套它的函数的变量。

但是如果函数A没有嵌套函数B中,函数A就看不到函数B的变量。

var myvar = "my value"; // <-- global variable, seen by all functions    
var zmienna = "string"; // <-- global variable, seen by all functions

(function () {
    alert(myvar);    // <-- referencing the global variable
    alert(zmienna);  // <-- referencing the global variable
})();
(function () {
    // v--- Declaration of these "local" variables were hoisted to the top...
    // var myvar;    // <--- ...as though it was here.
    // var new_var;  // <--- ...as though it was here.

    alert(myvar); // undefined (myvar is delcared, but not initialized)
    alert(new_var); // undefined (new_var is delcared, but not initialized)

    var myvar = "local value"; // <-- assign the value

    alert(zmienna);  // <-- referencing the global variable
    alert(myvar);  // <-- referencing the local variable

    var new_var = "test";  // <-- another new local variable

    // A nested function. It has access to the variables in its scope chain.
     (function() {
         alert(myvar);  // <-- referencing the variable from its parent func
         alert(new_var);  // <-- referencing the variable from its parent func
     })();
})();
/* 
Here's a new function. It was not nested inside the previous function, so it
   has access to the global variables, and not the locals of the previous func
*/
(function () {
    alert(myvar);    // <-- referencing the global variable
    alert(new_var);  // <-- ReferenceError
})();
Run Code Online (Sandbox Code Playgroud)