繁体   English   中英

为什么即使声明的变量中没有“ var”关键字,我仍会收到“ Uncaught ReferenceError”?

[英]why do i get “Uncaught ReferenceError” even though variable is declared without “var” keyword?

我遇到了以下代码片段:

 (function() { bar = 5; var bar = 10; console.log("value of bar inside the self invoking function = " + bar); })(); console.log("value of bar out of function scope " + bar); 

当我执行以上代码时,我得到:

“未捕获的ReferenceError”

对于第二个控制台

这是由于“可变提升”。 变量是在解析javascript时声明的,因此在执行时,引擎已经知道范围内将可用的所有变量,因此可以将它们分配给它们。 提升过程完成后,您的功能实际上如下所示。

 (function() { var bar; bar = 5; bar = 10; console.log("value of bar inside the self invoking function = " + bar); })(); console.log("value of bar out of function scope " + bar); 

您可以在MDN上阅读有关它的更多信息: https : //developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/var#var_hoisting

var声明的所有变量都将提升到声明它们的函数的顶部,因此,如果在函数内部定义了该变量,则它将移到该函数的顶部,并且如果在全局范围内定义了该变量,则移至全球环境的最顶端。

(function() {
    bar = 5;
    var bar = 10;
    console.log("value of bar inside the self invoking function = " + bar);
})();

在这里,在您的情况下,您已经在匿名函数中定义了变量,因此它将被移至该函数的顶部,并且在提升后将类似于

(function() {
    var bar;
    bar = 5;
    bar = 10;
    //...rest of the code
})();

但是此变量仅在该函数的本地范围内可用,而在全局范围内不可用。 这就是为什么当您尝试在全局范围内访问它时会收到Uncaught ReferenceError的原因。

这是一篇很好的文章,解释了JavaScript中的变量作用域和变量提升。 http://javascriptissexy.com/javascript-variable-scope-and-hoisting-explained/

需要注意的一件事是,只有使用var声明的变量才会被提升 如果您使用ES6 let关键字声明变量,则不会将其吊起。 所以

(function() {
    bar = 5;
    let bar = 10;
    console.log("value of bar inside the self invoking function = " + bar);
})();

将无法工作,并且您将收到相同的错误。 您可以在这里了解更多信息

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM