Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scope of javascript variable declared inline

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.

like image 953
Salman Haq Avatar asked Jun 06 '26 21:06

Salman Haq


2 Answers

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.

like image 93
Crescent Fresh Avatar answered Jun 08 '26 14:06

Crescent Fresh


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.

like image 32
Aaron Qian Avatar answered Jun 08 '26 16:06

Aaron Qian