여러 파일에서 Javascript의 전역 변수
내 JavaScript 코드는 helpers.js라는 외부 파일에 있습니다. 이 JavaScript 코드를 호출하는 HTML 내부에서 helpers.js의 특정 함수가 호출되었는지 여부를 알아야합니다.
다음을 정의하여 전역 변수를 만들려고했습니다.
var myFunctionTag = true;
내 HTML 코드와 helpers.js 모두 글로벌 범위에서.
내 HTML 코드는 다음과 같습니다.
<html>
...
<script type='text/javascript' src='js/helpers.js'></script>
...
<script>
var myFunctionTag = false;
...
//I try to use myFunctionTag here but it is always false, even though it has been se t to 'true' in helpers.js
</script>
내가 가능한 일을하려고합니까?
helpers.js 파일을 포함시키기 전에 변수를 선언해야합니다. include for helpers.js 위에 스크립트 태그를 작성하고 정의하십시오.
<script type='text/javascript' >
var myFunctionTag = false;
</script>
<script type='text/javascript' src='js/helpers.js'></script>
...
<script type='text/javascript' >
// rest of your code, which may depend on helpers.js
</script>
변수는 .js
파일 에서 선언 될 수 있고 HTML 파일에서 간단하게 참조 될 수 있습니다 . 내 버전 helpers.js
:
var myFunctionWasCalled = false;
function doFoo()
{
if (!myFunctionWasCalled) {
alert("doFoo called for the very first time!");
myFunctionWasCalled = true;
}
else {
alert("doFoo called again");
}
}
그리고 그것을 테스트 할 페이지 :
<html>
<head>
<title>Test Page</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<script type="text/javascript" src="helpers.js"></script>
</head>
<body>
<p>myFunctionWasCalled is
<script type="text/javascript">document.write(myFunctionWasCalled);</script>
</p>
<script type="text/javascript">doFoo();</script>
<p>Some stuff in between</p>
<script type="text/javascript">doFoo();</script>
<p>myFunctionWasCalled is
<script type="text/javascript">document.write(myFunctionWasCalled);</script>
</p>
</body>
</html>
You'll see the test alert()
will display two different things, and the value written to the page will be different the second time.
OK, guys, here's my little test too. I had a similar problem, so I decided to test out 3 situations:
- One HTML file, one external JS file... does it work at all - can functions communicate via a global var?
- Two HTML files, one external JS file, one browser, two tabs: will they interfere via the global var?
- One HTML file, open by 2 browsers, will it work and will they interfere?
All the results were as expected.
- It works. Functions f1() and f2() communicate via global var (var is in the external JS file, not in HTML file).
- They do not interfere. Apparently distinct copies of JS file have been made for each browser tab, each HTML page.
- All works independently, as expected.
Instead of browsing tutorials, I found it easier to try it out, so I did. My conclusion: whenever you include an external JS file in your HTML page, the contents of the external JS gets "copy/pasted" into your HTML page before the page is rendered. Or into your PHP page if you will. Please correct me if I'm wrong here. Thanx.
My example files follow:
EXTERNAL JS:
var global = 0;
function f1()
{
alert('fired: f1');
global = 1;
alert('global changed to 1');
}
function f2()
{
alert('fired f2');
alert('value of global: '+global);
}
HTML 1:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript" src="external.js"></script>
<title>External JS Globals - index.php</title>
</head>
<body>
<button type="button" id="button1" onclick="f1();"> fire f1 </button>
<br />
<button type="button" id="button2" onclick="f2();"> fire f2 </button>
<br />
</body>
</html>
HTML 2
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript" src="external.js"></script>
<title>External JS Globals - index2.php</title>
</head>
<body>
<button type="button" id="button1" onclick="f1();"> fire f1 </button>
<br />
<button type="button" id="button2" onclick="f2();"> fire f2 </button>
<br />
</body>
</html>
Hi to pass values from one js file to another js file we can use Local storage concept
<body>
<script src="two.js"></script>
<script src="three.js"></script>
<button onclick="myFunction()">Click me</button>
<p id="demo"></p>
</body>
Two.js file
function myFunction() {
var test =localStorage.name;
alert(test);
}
Three.js File
localStorage.name = 1;
I think you should be using "local storage" rather than global variables.
If you are concerned that "local storage" may not be supported in very old browsers, consider using an existing plug-in which checks the availability of "local storage" and uses other methods if it isn't available.
I used http://www.jstorage.info/ and I'm happy with it so far.
You can make a json object like:
globalVariable={example_attribute:"SomeValue"};
in fileA.js
And access it from fileB.js like: globalVariable.example_attribute
//Javascript file 1
localStorage.setItem('Data',10);
//Javascript file 2
var number=localStorage.getItem('Data');
Don't forget to link your JS files in html :)
참고URL : https://stackoverflow.com/questions/2932782/global-variables-in-javascript-across-multiple-files
'Programming' 카테고리의 다른 글
babel-preset-stage-0, babel-preset-stage-1 등의 차이점은 무엇입니까? (0) | 2020.07.17 |
---|---|
Java EE 컨테이너의 스폰 스레드가 권장되지 않는 이유는 무엇입니까? (0) | 2020.07.17 |
std :: atomic은 정확히 무엇입니까? (0) | 2020.07.17 |
파이썬에는 정렬 된 목록이 있습니까? (0) | 2020.07.17 |
RabbitMQ / AMQP : 단일 대기열, 동일한 메시지에 대한 여러 소비자? (0) | 2020.07.17 |