Javascript:跨不同Javascript文件的变量范围

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4022606/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 10:10:52  来源:igfitidea点击:

Javascript: Scope of a Variable across different Javascript files

javascriptscope

提问by User 1034

I defined a variable in one of my JavaScript files. I want to access the value of that variable among JavaScript files. In one file I am initializing the value of that variable.

我在我的一个 JavaScript 文件中定义了一个变量。我想在 JavaScript 文件中访问该变量的值。在一个文件中,我正在初始化该变量的值。

I cannot access the assigned value in another JS files.

我无法访问另一个 JS 文件中的分配值。

Is there anything that I am missing ?

有什么我想念的吗?

回答by alex

You should be able to access them if they are in the global scope or can be accessed from the global scope.

如果它们在全局范围内或可以从全局范围访问,您应该能够访问它们。

For example, I have a object literal like this in my HTML in a scriptelement...

例如,我的 HTMLscript元素中有一个像这样的对象文字......

<script type="text/javascript">
    var config = {
       basePath: '/path/'
    };
</script>

Which I can access in any other subsequent JavaScript file with config.basePath.

我可以在任何其他后续 JavaScript 文件中使用config.basePath.

回答by Nick Craver

It has to be a global variable, or accessible in the same scope (e.g. a property on something else that's global), and it has to be defined beforeyou're accessing it, meaning the order of your script includes matters.

它必须是一个全局变量,或者可以在同一范围内访问(例如,其他全局变量的属性),并且必须您访问它之前对其进行定义,这意味着您的脚本的顺序很重要。

You can't for instance have this in one file:

例如,您不能在一个文件中包含此内容:

(function() {
   var something = "blah";
})();

...and access it in the next file, since that variable is scoped to that function.

...并在下一个文件中访问它,因为该变量的范围是该函数。

回答by Zathrus Writer

also, once globally defined, you might need to be accessing it via the window object like this: window.your_variable OR window['your_variable']

此外,一旦全局定义,您可能需要像这样通过 window 对象访问它:window.your_variable OR window['your_variable']