由于我是一个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变量.好吧,前两个警报说正确的值.这很奇怪,因为第三个警报说"未定义",尽管事实上之前的功能块没有任何变化.第四个,再次打印正确的价值.
有谁能解释一下,这里发生了什么?我会很高兴,因为教程没有更多关于这一点.
“我读到 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)
| 归档时间: |
|
| 查看次数: |
384 次 |
| 最近记录: |