Javascript: Scope of a Variable across different Javascript files

99封情书 提交于 2019-12-18 04:12:57

问题


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.

I cannot access the assigned value in another JS files.

Is there anything that I am missing ?


回答1:


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 script element...

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

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




回答2:


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 before you'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.




回答3:


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



来源:https://stackoverflow.com/questions/4022606/javascript-scope-of-a-variable-across-different-javascript-files

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!