Miles
Miles

Reputation: 2537

Javascript reuse of a function

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>

Upvotes: 1

Views: 1360

Answers (5)

hugomg
hugomg

Reputation: 69984

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.

Upvotes: 1

Alec Gorge
Alec Gorge

Reputation: 17420

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

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1075885

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).

Upvotes: 3

SLaks
SLaks

Reputation: 888293

Yes.

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

Upvotes: 3

Oded
Oded

Reputation: 499392

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

Upvotes: 4

Related Questions