1

If you have one HTML file, that has multiple scripts linked in the header, can one script later on invoke functions from another? Assuming that they are included in the HTML page as so:

<script type="text/javascript" src="scripts/StyleSelector.js"></script>

5 Answers 5

4

Yes, a script in one file can call a function in another, so long as the scripts being called have all been fully loaded.

Sign up to request clarification or add additional context in comments.

Comments

3

Yes. There is one JavaScript environment for a page, and within that environment there is one global scope. If functions are declared at the top level of a script file, they are added to that one global scope, regardless of which script file they came from. There is no distinction between global functions in one file and global functions in another. And of course, any function that can get a reference to another (e.g., from the global scope) can execute it.

This is, of course, how libraries work. You load (say) jQuery from one script file (probably from a CDN, Google's or Microsoft's), and then you use it from another script file (your own).

Comments

3

Yes.

All Javascript code in a page executes in the same global context.

Comments

1

Yes they can. They all are contained within the same global scope.

1 Comment

That is what I meant by what I wrote, but I can see how that might not be clear.
1

Yes, they share the same global variables and doing so is one of the accepted ways to do modules in Javascript

<script src="jquery.js"></script>  <!-- Include the jQuery library.
                                        Creates a global jQuery variable -->
<script src="mycode.js"></script>  <!-- code uses the jQuery
                                        via that global variable -->

Do note that since global variables are shared, when writing your own scripts you should try your best to only use globals only when strictly necessary, in order to avoid accidental naming clashes.

A common pattern is wrapping your code inside an immediately invoked function in order to turn things into local variables instead of globals.

//instead of littering the global namespace

var myVar = /*...*/
function f1(){ /*...*/ }
function f2(){ /*...*/ }

//Put the related stuff in a namespaced module.

var myModule = (function(){
    var myVar = /*...*/
    function f1(){ /*...*/ }
    function f2(){ /*...*/ }

    return {
        f1: f1,
        f2: f2
    };
}());

//myModule is now a global "namespace" object containing just your public
// stuff inside it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.