Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I can't access a JavaScript function defined in a .js file from another .js file?

I am pretty new to JavaScript, and I was experimenting with the global scope following a tutorial.

In this tutorial I have 3 files:

1) index.htm:

<html>
    <head></head>

    <body>
        <h1>HELLO WORLD !!!</h1>

        <script src="app.js"></script>
        <script src="utility.js"></script>

    </body>
</html>

As you can see I include 2 JavaScript files.

2) app.js:

var person = 'Torny';   // When I call the logPerson() function this line override the person variable value into the global stack

//console.log(person);

logPerson();

3) utility.js in which is defined the logPerson() function defined into the app.js file:

var person = 'Steve';

function logPerson() {
    console.log(person);
}

Ok, so I expected the following behavior:

Into the app.js file set the string 'Tony' as value of the person variable, the call the logPerson() function declared into the utility.js file and so print 'Tony' in the console.

The problem is that when I try to open the index.htm file into FireFox, I go into FireBug console and instead the 'Tony' value I obtain this error message:

ReferenceError: logPerson is not defined

So it seems that from the app.js file it can't see the logPerson() function that is defined into the utility.js file and imported.

Why? What am I missing? what is wrong?

like image 756
AndreaNobili Avatar asked Nov 30 '22 10:11

AndreaNobili


2 Answers

In javascript the order of the files matters. You need to load the script which defines your function before you can use it. Switch the 2 <script> tags

<body>
    <h1>HELLO WORLD !!!</h1>

    <script src="utility.js"></script>
    <script src="app.js"></script>

</body>
</html>
like image 139
element11 Avatar answered Dec 09 '22 19:12

element11


change

<script src="app.js"></script>
<script src="utility.js"></script>

to

<script src="utility.js"></script>
<script src="app.js"></script>

;) You try to get definitions from a script which is loaded later greetings

like image 42
messerbill Avatar answered Dec 09 '22 21:12

messerbill