-2

I want to know whether I can access variables in one in a separate in the same HTML file. The below code is to give an example of what I am trying to do. It doesn't work at all though but it should help to see what I want to do

<script type="text/javascript" id="script1">
    otherScript = document.getElementById("script2")
    number1=otherScript.someNumber
</script>


<script type="text/javascript" id="script2">
    someNumber=7
</script>
Mouser
  • 13,132
  • 3
  • 28
  • 54
  • The script tags that you use to in HTML have nothing to do with how your javascript is scoped, or "moduled". Your javascript within both tags will be in the global scope, unless you explicitly create module objects for your code. Because of this most client-side javascript libs will expose a single global accessor ($, _, angular, ko) to the public API. – Martin Dec 27 '14 at 17:23

1 Answers1

0

Please read into the scope of a program. Both scripts are on the same page and share the same global scope. You can access someNumber from script block 21, but not fromscript block 1` the way you've wrote it:

The scope begins with parsing script block 1. Script block 2 doesn't exist at this moment.

An example to help you further

<script type="text/javascript" id="script1">
    number1=someNumber; //this will generate an error;
    function alertNumber()
    {
        //this isn't executed directly because it's a function. 
        //We call upon it later in script block 2.
        alert(someNumber); //this will work.
    }
</script>


<script type="text/javascript" id="script2">
    someNumber=7;

    alertNumber(); // alertNumber exists since script block 1 is parsed.
</script>

As you can see the flow of the document is top-down. Objects that are in the same scope needs to be declared first before they are called upon. In your code someNumber wasn't declared yet.

A good page on scope is also on this site.

Community
  • 1
  • 1
Mouser
  • 13,132
  • 3
  • 28
  • 54