看似定义 javascript 变量抛出未定义的错误

Seemingly defined javascript variable throws undefined error

鉴于以下代码,我不确定为什么我可以检索 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 包含此代码,试图找出另一个 LongAndObscureVariableName 的值:

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 中检索到另一个 LongAndObscureVariableName,尽管我认为我是通过将其放入 HTML 文档的头部来将其添加到全局范围。

这是范围问题吗?这是 timing/sequencing 问题吗?我认为 jsFileNumberTwo.js 可能在 jsFileNumberOne.js 执行之前访问头部内容,但即使添加了 setTimeout 函数我仍然得到 "undefined".

这是怎么回事?我怎样才能使这项工作?

脚本从上到下 运行ning。所以第二个脚本修改了第一个,它已经 运行 并且不会再次 运行,所以实际上没有效果。

此外,你应该把东西放在 window 上来制作全局变量。

所以替换

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

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

insertNewInfo();

window.anotherLongAndObscureVariableName = "bar";

,

var longAndObscureVariableName = "foo";

window.longAndObscureVariableName = "foo";

与其添加到 jsfileNumberOne.js 中的现有脚本元素,不如仅在该文件中包含全局变量。在你的 jsfileNumberOne.js 中,只需像这样包含全局变量:

window.anotherLongObscureVariableName = "bar";