我可以从另一个文件访问变量吗? [英] Can I access variables from another file?
本文介绍了我可以从另一个文件访问变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以在另一个名为 second.js
的文件中使用名为 first.js
的文件中的变量?
Is it possible to use a variable in a file called first.js
inside another file called second.js
?
first.js
包含一个名为 colorcodes
的变量.
first.js
contains a variable called colorcodes
.
推荐答案
正如 Fermin 所说,全局范围内的变量应该可以被声明后加载的所有脚本访问.您还可以使用 window
或(在全局范围内)this
的属性来获得相同的效果.
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 window
or (in the global scope) this
to get the same effect.
// first.js
var colorCodes = {
back : "#fff",
front : "#888",
side : "#369"
};
...在另一个文件...
... in another file ...
// second.js
alert(colorCodes.back); // alerts `#fff`
... 在您的 html 文件中...
... in your html file ...
<script type="text/javascript" src="first.js"></script>
<script type="text/javascript" src="second.js"></script>
这篇关于我可以从另一个文件访问变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文