var devices_re...">

Javascript inline variable scope

Here are the problem scenarios:

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 HttpFox error report is that the device_ entry is not defined. What gives? I thought the device_ entry would be a variable with global scope, so it should be accessible from anywhere.

+3
source share
3 answers

The test version 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 warnings, the first says the "some string"second "assign new string".

Your problem exists elsewhere in your code.

+3
source

, . , , , .

, , foo.js, js. , .

, "device_ record not defined", .

, - .

+1

devices_record foo.js. javascript, HTML.

foo.js devices_record /. .

Tidbit: also, if the device_record declaration was placed before the script was included, the script may have access to it. However, be careful with declaring variables outside the file that uses them. If you decide to include this script on a page that forgets to declare device_record, you will encounter errors.

0
source

Source: https://habr.com/ru/post/1716241/


All Articles