我不认为我的问题与 How do I return the response from an asynchronous call? 重复
在其他语言(C#)中,我看到了一个变量声明 在函数或循环中,当您退出函数或循环时,它们无法访问已在其他函数中声明的变量,但在 javascript 中可以。
$(document).ready(function () {
Text();
Tex2();
});
function Text() {
for (xxi = 0; xxi < 10; xxi++) {
console.log(xxi);
iix = 99;
}
console.log(xxi + iix);
Tex2();
}
function Tex2() {
console.log("What the hel:" + (xxi + iix));
}
结果是:
最佳答案
您在不使用 var
关键字的情况下将它们声明为全局变量。使用 var
关键字将它们限定在预期范围内,或在 javascript 文件之上使用 "use strict"
。您还可以使用 let
关键字将它们限定在它们的本地范围内。
不使用 var and let keywords 声明的变量具有全局范围。
使用 var 关键字声明的变量被 javascript 视为其封闭范围或函数内的第一条语句。因此,无论 block 作用域如何,它都为整个函数全局或局部定义了一个变量。
let 关键字允许将变量声明在使用它的 block 、语句或表达式的范围内。
I have created 3 snippets below. one with
let
keyword, one withvar
keyword, and one withuse strict
keyword over your code. Run to see changing behavior of same code piece.
下面的片段
let
keyword snippet. Run to see that variable is not available outside block scope even.//let keyword snippet. See variable is not available outside block scope even. $(document).ready(function () { Text(); Tex2(); }); function Text() { for (let xxi = 0; xxi < 10; xxi++) { console.log(xxi); let iix = 99; } var xyz; try { xyz = xxi + iix; } catch (e){ xyz = e; } console.log(xyz); Tex2(); } function Tex2() { var abc; try { abc = (xxi + iix); } catch (e){ abc = e; } console.log("What the hel:" + abc); }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
var
keyword snippet. Run to see that variable is not available outside function scope.//var keyword snippet. See variable is not available outside function scope. $(document).ready(function () { Text(); Tex2(); }); function Text() { for (var xxi = 0; xxi < 10; xxi++) { console.log(xxi); var iix = 99; } var xyz; try { xyz = xxi + iix; } catch (e){ xyz = e; } console.log(xyz); Tex2(); } function Tex2() { var abc; try { abc = (xxi + iix); } catch (e){ abc = e; } console.log("What the hel:" + abc); }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
use strict
keyword snippet. Run to see that it will not run at all. This is your code with use strict.
//Your snippet with "use strict". Will not work at all.
"use strict"
$(document).ready(function () {
Text();
Tex2();
});
function Text() {
for (xxi = 0; xxi < 10; xxi++) {
console.log(xxi);
iix = 99;
}
console.log(xxi + iix);
Tex2();
}
function Tex2() {
console.log("What the hel:" + (xxi + iix));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
关于javascript - 为什么javascript可以理解函数和循环外的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46742333/