1

I would like to be able to access from anywhere in my javascript code a global list of strings defined in javascript.

For example I'd like to define a script like this :

<script type="text/javascript">
    function translations()
    {
        this.mytranslation = "Test translation";
        this.mytranslation2 = "Test translation 2";
        this.mytranslation3 = "Test translation 3";
    }

    function messages()
    {
        this.mymessage = "Test message";
        this.message2 = "Test message 2";
    }
</script>

The code above doesn't work, it's just here to present the kind of thing I would like.

And I want to be able to call it simply by :

alert(translations.mytranslation);

and

alert(messages.message2);

from all other scripts (as long as the first one have been included of course)

I would like something that works with Internet Explorer 11 (no actual classes support) and above.

Thanks for your advices

AFract
  • 8,868
  • 6
  • 48
  • 70
  • You 'd better use `window.myVar` or define it outside the function initially. See: https://stackoverflow.com/q/5786851/4636715 – vahdet Mar 11 '19 at 11:14

3 Answers3

2

Better use global object instead of function

  • you are defined the function but you are calling translations.mytranslation.SO object only suitable

var translations  = {
         mytranslation : "Test translation",
         mytranslation2 : "Test translation 2",
         mytranslation3 : "Test translation 3",
    }

    
 console.log(translations.mytranslation)
prasanth
  • 22,145
  • 4
  • 29
  • 53
1

You can try this constructor method:

function translations() {
  this.mytranslation = "Test translation";
  this.mytranslation2 = "Test translation 2";
  this.mytranslation3 = "Test translation 3";
}

function messages() {
  this.mymessage = "Test message";
  this.message2 = "Test message 2";
}

alert(new translations().mytranslation);
alert(new messages().message2);
O.O
  • 1,389
  • 14
  • 29
0

You could return 'this' from the function i.e.

function translations()
{
    this.mytranslation = "Test translation";
    this.mytranslation2 = "Test translation 2";
    this.mytranslation3 = "Test translation 3";
    return this;
}
const mytrans = translations();
console.log(mytrans.mytranslation2);

You would need to store the returned object somewhere sensible.

Liam MacDonald
  • 301
  • 1
  • 9