Javascript 我可以从另一个文件访问变量吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3244361/
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
Can I access variables from another file?
提问by SAK
Is it possible to use a variable in a file called first.jsinside another file called second.js?
是否可以first.js在另一个名为的文件中调用的文件中使用变量second.js?
first.jscontains a variable called colorcodes.
first.js包含一个名为 的变量colorcodes。
回答by Dagg Nabbit
As Fermin said, a variable in the global scope should be accessible to all scripts loaded after it is declared. You could also use a property of windowor (in the global scope) thisto get the same effect.
正如 Fermin 所说,全局范围内的变量应该可以被声明后加载的所有脚本访问。您还可以使用windowor (在全局范围内)的属性this来获得相同的效果。
// first.js
var colorCodes = {
back : "#fff",
front : "#888",
side : "#369"
};
... in another file ...
...在另一个文件...
// second.js
alert (colorCodes.back); // alerts `#fff`
... in your html file ...
...在您的 html 文件中 ...
<script type="text/javascript" src="first.js"></script>
<script type="text/javascript" src="second.js"></script>
回答by Germa Vinsmoke
You can export the variable from first file using export.
您可以使用export从第一个文件导出变量。
//first.js
const colorCode = {
black: "#000",
white: "#fff"
};
export { colorCode };
Then, import the variable in second file using import.
然后,使用import在第二个文件中导入变量。
//second.js
import { colorCode } from './first.js'
回答by Basheer AL-MOMANI
I did like what answer abovesaid but although, it didn't worked with me
because I was declaringthese variables insideJQuery $( document ).ready()
因为我是JQuery 的declaring这些变量inside$( document ).ready()
so make sure you declare your variables inside the
<script>tag not somewhere else
所以确保你在
<script>标签内而不是其他地方声明你的变量
回答by Piskvor left the building
This should work - define a global variable in firstfile and access it from secondfile:
这应该有效 - 在 firstfile 中定义一个全局变量并从 secondfile 访问它:
<script src="/firstfile.js"></script>
<script src="/secondfile.js"></script>
firstfile.js:
第一个文件.js:
var colors = {
text:'#000000',
background:'#aaaaaa',
something_else:'blue'
};
secondfile.js:
第二个文件.js:
do_something_with(colors.background);
Note that the order in which you load the script files is significant for some browsers (IE6 for sure, maybe others)
请注意,加载脚本文件的顺序对于某些浏览器很重要(当然是 IE6,也可能是其他浏览器)
回答by Xinton
Using Node.js you can export the variable via module.
使用 Node.js,您可以通过模块导出变量。
//first.js
const colorCode = {
black: "#000",
white: "#fff"
};
module.exports = { colorCode };
Then, import the module/variable in second file using require.
然后,使用 require 在第二个文件中导入模块/变量。
//second.js
const { colorCode } = require('./first.js')
You can use the importand exportaproach from ES6 using Webpack/Babel, but in Node.js you need to enable a flag, and uses the .mjs extension.
您可以使用Webpack/Babel 使用 ES6 中的import和export方法,但在 Node.js 中您需要启用一个标志,并使用 .mjs 扩展名。
回答by Ben Leitner
I came across amplify.js. It's really simple to use. To store a value, let's call it "myValue", you do:
我遇到了amplify.js。使用起来真的很简单。要存储一个值,我们称之为“myValue”,你可以:
amplify.store("myKey", "myValue")
And to access it, you do
要访问它,您可以
amplify.store("myKey")
回答by Fermin
If you store your colorcodes in a global variable you should be able to access it from either javascript file.
如果您将颜色代码存储在全局变量中,您应该能够从任一 javascript 文件访问它。
回答by Alan
I may be doing this a little differently. I'm not sure why I use this syntax, copied it from some book a long time ago. But each of my js files defines a variable. The first file, for no reason at all, is called R:
我的做法可能有点不同。我不确定为什么要使用这种语法,很久以前从某本书中复制了它。但是我的每个 js 文件都定义了一个变量。第一个文件无缘无故地被称为 R:
var R =
{
somevar: 0,
othervar: -1,
init: function() {
...
} // end init function
somefunction: function(somearg) {
...
} // end somefunction
...
}; // end variable R definition
$( window ).load(function() {
R.init();
})
And then if I have a big piece of code that I want to segregate, I put it in a separate file and a different variable name, but I can still reference the R variables and functions. I called the new one TD for no good reason at all:
然后,如果我有一大段代码要隔离,我会将它放在一个单独的文件和不同的变量名中,但我仍然可以引用 R 变量和函数。我毫无理由地打电话给新的 TD:
var TD =
{
xvar: 0,
yvar: -1,
init: function() {
...
} // end init function
sepfunction: function() {
...
R.somefunction(xvar);
...
} // end somefunction
...
}; // end variable TD definition
$( window ).load(function() {
TD.init();
})
You can see that where in the TD 'sepfunction' I call the R.somefunction. I realize this doesn't give any runtime efficiencies because both scripts to need to load, but it does help me keep my code organized.
您可以看到我在 TD 'sepfunction' 中调用 R.somefunction 的位置。我意识到这不会带来任何运行时效率,因为这两个脚本都需要加载,但它确实帮助我保持代码井井有条。
回答by Karan Shaw
One best way is by using window.INITIAL_STATE
一种最好的方法是使用窗口。INITIAL_STATE
<script src="/firstfile.js">
// first.js
window.__INITIAL_STATE__ = {
back : "#fff",
front : "#888",
side : "#369"
};
</script>
<script src="/secondfile.js">
//second.js
console.log(window.__INITIAL_STATE__)
alert (window.__INITIAL_STATE__);
</script>

