Amith Mendis
Amith Mendis

Reputation: 145

How to create javascript globally accessible static variable?

I want to create a globally accessible variable. It must change when we want to change. After change it must give the changed value.

var language ="english";

function getGlobalVar(varName) {
    if(varName == "language"){
        return language;
    }
}

function setGlobalVar(varName, value) {
    if(varName == "language"){
       language = value;
    }
}

When we use getGlobalVar("language") in other pages, It must give the changed value.

Upvotes: 2

Views: 14513

Answers (4)

Josh Desmond
Josh Desmond

Reputation: 690

With ES15, you can now simply have classes with static variables:

class ClassWithGlobalVariable {
  static language = 'en';
}

console.log(ClassWithGlobalVariable.language);
ClassWithGlobalVariable.language = 'cn';
console.log(ClassWithGlobalVariable.language);

Upvotes: 0

Tito
Tito

Reputation: 9044

Another solution for most browsers which support local storage.

JStorage - store data locally with JavaScript

Upvotes: 0

7stud
7stud

Reputation: 48599

When we use getGlobalVar("language") in other pages, It must give the changed value

The web uses a stateless protocol, i.e. information does not persist from page to page. To get around that, you can use cookies on the client side or server side solutions like sessions.

Try this:

1.htm

<script type="text/javascript">
    window.val = "hello world";
    alert(window.val);
    window.location.href = "2.htm"
</script>

2.htm

  <script type="text/javascript">
    alert(window.val);
  </script>

cookie example:

1.htm

<script type="text/javascript">
    var in_one_year = new Date();
    in_one_year.setFullYear(in_one_year.getFullYear() + 1);
    document.cookie = "language=English" +
                      ";expires=" + in_one_year.toGMTString();


    all_cookies = document.cookie
    alert(all_cookies);
    window.location.href = "2.htm"
</script>

2.htm

<script type="text/javascript">
    alert(document.cookie);
</script>

Upvotes: 2

elclanrs
elclanrs

Reputation: 94101

A global variable is just a variable attached to window:

window.language = 'english';

function getGlobalVar(bar) {
  return window[bar];
}

It's recommended that you create your own namespace to avoid problems later on:

window.MY = {};
MY.language = 'english';

Upvotes: 5

Related Questions