Robin Carlo Catacutan
Robin Carlo Catacutan

Reputation: 13679

Call variables from one javascript file to another

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);

Upvotes: 14

Views: 44621

Answers (3)

Pastor Bones
Pastor Bones

Reputation: 7351

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());

Upvotes: 2

ExpExc
ExpExc

Reputation: 3926

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>

Upvotes: 2

Adam Rackis
Adam Rackis

Reputation: 83358

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, 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

Upvotes: 12

Related Questions