admin管理员组文章数量:1194361
How can I call the variables that I stored in one javascript file from another?
var.js
var VAR = new Object;
VAR.myvalue = "Yeah!";
then I want to use VAR.myvalue here
sample.js
alert(VAR.myvalue);
How can I call the variables that I stored in one javascript file from another?
var.js
var VAR = new Object;
VAR.myvalue = "Yeah!";
then I want to use VAR.myvalue here
sample.js
alert(VAR.myvalue);
Share
Improve this question
edited Dec 2, 2011 at 3:42
Kevin
56k15 gold badges105 silver badges136 bronze badges
asked Dec 2, 2011 at 3:01
Robin Carlo CatacutanRobin Carlo Catacutan
13.7k12 gold badges54 silver badges86 bronze badges
2
|
3 Answers
Reset to default 12First, instead of
var VAR = new Object;
VAR.myvalue = "Yeah!";
Opt for
var VAR = {
myvalue: "Yeah!"
};
But so long as var.js
is referenced first, before sample.js, what you have should work fine.
var.js will declare, and initialize VAR, which will be read from the script declared in sample.js
Include both JavaScript file in one HTML file, place sample.js
after var.js
so that VAR.myvalue
is valid:
<script type="text/javascript" src="var.js"></script>
<script type="text/javascript" src="sample.js"></script>
Try separating your scope using a module pattern. This will eliminate headaches in the future.
var.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
someVar.add(5);
someVar.sub(6);
alert(someVar.total());
本文标签: Call variables from one javascript file to anotherStack Overflow
版权声明:本文标题:Call variables from one javascript file to another - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738489415a2089616.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
alert
somewhere it's sure to get called? – Kevin Commented Dec 2, 2011 at 3:42