将变量从一个 javascript 文件调用到另一个
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8351265/
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
Call variables from one javascript file to another
提问by Robin Carlo Catacutan
How can I call the variables that I stored in one javascript file from another?
如何从另一个 javascript 文件中调用我存储在一个 javascript 文件中的变量?
var.js
变量.js
var VAR = new Object;
VAR.myvalue = "Yeah!";
then I want to use VAR.myvalue here
那么我想在这里使用 VAR.myvalue
sample.js
示例.js
alert(VAR.myvalue);
采纳答案by Adam Rackis
First, instead of
首先,而不是
var VAR = new Object;
VAR.myvalue = "Yeah!";
Opt for
选择
var VAR = {
myvalue: "Yeah!"
};
But so long as var.js
is referenced first, beforesample.js, what you have should work fine.
但是,只要var.js
被引用首先,之前sample.js,你有什么应该工作的罚款。
var.js will declare, and initialize VAR, which will be read from the script declared in sample.js
var.js 将声明并初始化 VAR,它将从 sample.js 中声明的脚本中读取
回答by ExpExc
Include both JavaScript file in one HTML file, place sample.js
after var.js
so that VAR.myvalue
is valid:
将两个 JavaScript 文件包含在一个 HTML 文件中,放在sample.js
后面var.js
以便VAR.myvalue
有效:
<script type="text/javascript" src="var.js"></script>
<script type="text/javascript" src="sample.js"></script>
回答by Pastor Bones
Try separating your scope using a module pattern. This will eliminate headaches in the future.
尝试使用模块模式分离您的范围。这将消除未来的头痛。
var.js
变量.js
var someVar = (function () {
var total = 10; // Local scope, protected from global namespace
return {
add: function(num){
total += num;
}
, sub: function(num){
total -= num;
}
, total: function(){
return total;
}
};
}());
Then you can use that object's methods and properties from anywhere else.
然后您可以从其他任何地方使用该对象的方法和属性。
sample.js
示例.js
someVar.add(5);
someVar.sub(6);
alert(someVar.total());