简体   繁体   中英

Javascript variable between two external files

I'm new to JS, and I don't understand why this doesn't work. The following is in a file called test1.js

var greeting;

function randomGreeting(){
    var greet = new Array("BORING JS TEST ALERT", "EXCITING JS TEST ALERT", "AWESOME JS TEST ALERT");
    var randGreet = Math.floor(Math.random() * greet.length);

    greeting = {
        alert: greet[randGreet]
    };
}

In a separate test2.js file:

alert(greeting.alert);

In my HTML I have randomGreeting() being called in the body's onLoad , and I have test1.js loaded before test2.js , but I still get undefined from the console when test2 is ran. Why?

you have a race condition against test2.js running and the document onload event which fires much later.

You either delay the alert until the variable is set

(function(){
   if (typeof greeting == "undefined")
      return window.setTimeout(arguments.callee, 10);

   alert(greeting.alert);
}());

if you're not recalling randomGreeting, you can just inline it

var greet = new Array("BORING JS TEST ALERT", "EXCITING JS TEST ALERT", "AWESOME JS TEST ALERT");
var randGreet = Math.floor(Math.random() * greet.length);
var greeting = {
    alert: greet[randGreet]
};

Or you can change the scripts to use the defer attribute

<script scr="test1.js"></script>
<script scr="test2.js" defer></script>
<script>
window.onload = function(){
    alert(greeting.alert);
};
</script>

Use Immediate Invoking Function:

You could wrap your randomGreeting() in an immediate invoking function code block to get it executed as soon as it's declared and thus your code will work:

var greeting;

(function randomGreeting(){
    var greet = new Array("BORING JS TEST ALERT", "EXCITING JS TEST ALERT", "AWESOME JS TEST ALERT");
    var randGreet = Math.floor(Math.random() * greet.length);

    greeting = {
        alert: greet[randGreet]
    };
})();

In a separate test2.js file:

alert(greeting.alert);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM