javascript - 看似已定义的 JavaScript 变量会引发未定义的错误

标签 javascript scope undefined

鉴于以下代码,我不确定为什么我可以检索 longAndObscureVariableName 但不能检索 anotherLongObscureVariableName。您能否解释一下,并展示如何使 anotherLongObscureVariableName 可从 jsFileNumberTwo.js 访问?

HTML 文档的头部最初包含:

<script type="text/javascript" id="my_globals">
var longAndObscureVariableName = "foo";
</script>

<script type="text/javascript" src="jsFileNumberOne.js" /></script>
<script type="text/javascript" src="jsFileNumberTwo.js" /></script>

Javascript 文件 jsFileNumberOne.js 包含以下代码,它将另一个全局变量添加到 #my_globals 元素中:

jQuery(document).ready(function() {

    // Store the initial variables, to which we will add more
    var initialVars = jQuery('#my_globals').html();
    // Define content for script tag:
    var scriptContent = initialVars;
    // Add to the script content
    scriptContent += 'var anotherLongObscureVariableName = "bar";\n';

    function insertNewInfo() {
        jQuery('#my_globals').html(scriptContent);
    };

    insertNewInfo();
});

当 jsNumberOne.js 执行时,#my_globals 更改为:

<script type="text/javascript" id="my_globals">
var longAndObscureVariableName = "foo";
var anotherLongAndObscureVariableName = "bar";
</script>

Javascript 文件 jsFileNumberTwo.js 包含此代码,试图找出 anotherLongAndObscureVariableName 的值:

jQuery(document).ready(function($) {
    console.log('longAndObscureVariableName'); // log displays "foo"
    console.log('anotherLongAndObscureVariableName'); // log displays "Uncaught ReferenceError: anotherLongAndObscureVariableName is not defined"
    console.log('window.anotherLongAndObscureVariableName'); // log displays "undefined"
    setTimeout(function(){
        console.log(window.anotherLongAndObscureVariableName);
    },2000); // log still displays "undefined"
});

我无法从 jsFileNumberTwo.js 中检索 anotherLongAndObscureVariableName,即使我认为我是通过将其放入 HTML 文档的头部来将其添加到全局范围的。

这是范围问题吗?这是时间/顺序问题吗?我认为 jsFileNumberTwo.js 可能在 jsFileNumberOne.js 执行之前访问头部内容,但即使添加了 setTimeout 函数,我仍然得到“未定义”。

这是怎么回事?我怎样才能做到这一点?

最佳答案

脚本从上到下运行。因此第二个脚本修改了第一个脚本,该脚本已经运行并且不会再次运行,因此实际上没有任何效果。

此外,您应该在窗口上放置一些东西来创建全局变量。

所以替换

scriptContent += 'var anotherLongObscureVariableName = "bar";\n';

function insertNewInfo() {
    jQuery('#my_globals').html(scriptContent);
};

insertNewInfo();

window.anotherLongAndObscureVariableName = "bar";

var longAndObscureVariableName = "foo";

window.longAndObscureVariableName = "foo";

关于javascript - 看似已定义的 JavaScript 变量会引发未定义的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31884772/

相关文章:

javascript - Sweet.js 的惰性求值宏

c++ - 功能范围不正确的输出

c++ - Visual Assert 的范围问题

javascript - 为什么这个 javascript 是行是正确的而另一个不是

methods - 将数据输入到输入<Selenium |瓦提尔 ruby >

javascript - 如何根据用户请求生成多个输入?

javascript - 从浏览器中隐藏 API key

javascript - React CSSTransitionGroup 不为高度、宽度或顶部设置动画

pointers - 我是如何混淆 goroutine 中变量和指针的范围的?

JQUERY 未定义