전역 변수를 생성하려면 해당 변수를 <script></script> 태그 내부에 선언해야 합니다. $(document).ready() 블록 안에 변수를 선언하면 지역 변수가 되어 외부 함수에서 접근할 수 없기 때문입니다.
아래 예제 코드를 통해 자세히 살펴보겠습니다.
예제
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<title>Document</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<button onclick="createGlobalVariable()">checkGlobalVariable</button>
<script>
var globalVariable;
$(document).ready(function() {
function initializeGlobalVariable() {
globalVariable = [{
"name":"John",
"age":23
}];
}
initializeGlobalVariable();
});
function createGlobalVariable() {
if (globalVariable.length) {
console.log('The Global variable name is='+globalVariable[0].name+" The Global variable age is="+globalVariable[0].age);
}
}
</script>
</body>
</html>코드 설명
var globalVariable;은 <script> 태그 바로 아래, 즉 document.ready 함수 외부에 선언되어 있으므로 전역 변수 역할을 합니다. 이후 document.ready 내부의 initializeGlobalVariable() 함수가 이 전역 변수에 값을 할당합니다. 버튼 클릭 시 실행되는 createGlobalVariable() 함수는 전역 변수에 접근하여 콘솔에 값을 출력할 수 있습니다.
실행 방법
위 프로그램을 실행하려면 파일 이름을 "anyName.html(index.html)"로 저장한 후, 파일을 마우스 오른쪽 버튼으로 클릭하세요. 그다음 VS Code 편집기에서 "Open with Live Server" 옵션을 선택하면 됩니다.
출력 결과
위 코드를 실행하면 다음과 같은 화면이 나타납니다.

버튼 checkGlobalVariable을 클릭하면 콘솔에 다음과 같은 출력 결과가 표시됩니다.
