views:

325

answers:

3

Here are the problem scripts:

This is from the HTML file:

<script type="text/javascript">
    var devices_record = "some string";
</script>
<script type="text/javascript" src="/js/foo.js"></script>

This is from foo.js:

function bar () {
    devices_record = "assign new string";
}

The error report by HttpFox is that devices_ record is not defined. What gives? I thought devices_ record will be a globally scoped variable so it should be accessible from anywhere.

A: 

Declare devices_record in foo.js. Then, reference it from the javascript embedded in the HTML.

You may also consider wrapping your foo.js code in a class, with devices_record as a field/property. This can make for much easier error trapping, among other things.

Tidbit: also, if devices_record declaration were placed before the script inclusion, the script may be able to access it. However, be wary of declaring variables outside of the file that uses them. If you decided to include that script in a page that forgets to declare devices_record, you'll run into errors.

David Lively
+1  A: 

I believe your given code works. At least executing the code you give above will not cause any errors.

Also, it's better to include your dependencies such as foo.js before using any inline js. This ensures your library is loaded before calling functions provided your library.

Also, assignment operators will not cause 'devices_ record is not defined' errors because you ARE defining it with the assignment operator.

Your error is probably caused by something else.

Aaron Qian
Good point about the assignment. Shows the asker is omitting the real code that is generating the error.
Crescent Fresh
+3  A: 

Your test case works for me. Here is my complete test:

foo.js:

function bar () {
    alert(devices_record);
    devices_record = "assign new string";
    alert(devices_record);
}

foo.html:

<html>
<head>
    <script type="text/javascript">
    var devices_record = "some string";
    </script>
    <script type="text/javascript" src="foo.js"></script>
</head>
<body onload="bar()">
</body>

I get two alerts, the first says "some string", the second "assign new string".

Your problem exists elsewhere in your code.

Crescent Fresh
You are right. The problem did exist else where in the code. Thank you.
Salman Haq