
👉 스코프 → 클로저
*함수는 자바스크립트에서 클로저 역할을 하기 때문에 스코프를 생성하므로 함수 내에 정의된 변수는 외부 함수나 다른 함수 내에서는 접근 할 수 없다.*
var globalVar = "I am a global variable";
function outerFunction() {
var outerVar = "I am in the outer function";
console.log(innerVar); // innerVar is not defined
function innerFunction() {
var innerVar = "I am in the inner function";
console.log(outerVar); // I am in the outer function
}
innerFunction();
}
outerFunction();정적 스코프(렉시컬 스코프) ✅Javascript
function name () {
var name = "Janet";
}
function getName () {
console.log(name);
}
getName(); // undefined
동적 스코프
함수를 호출한 시점에 스코프를 결정한다. “어디서 호출” 했느냐에 따라 함수 유효범위가 달라짐
Lisp, Emacs Lisp, Perl
var name = "Tom"
function myName () {
var name = 'Janet';
getName();
}
function getName() {
console.log(name);
}
myName(); // Janet
전역 변수*에 대해 접근과 조작이 가능한 유효한 범위
⇒ 전역 변수* : 어떠한 함수에도 속하지 않은 상태이고, 어떠한 중괄호 안에 들어있지 않은 상태
let global = "Global"; // 전역 변수
function scope () {
let local = "Local!"; // 지역 변수
console.log(global);
}
scope(); // Global!
console.log(local); // local is not defined
• var로 선언된 변수, 함수들은 함수 레벨 스코프가 된다.
function hi (name) {
if (name) {
var greeting = "Hello" + name;
}
console.log(greeting);
}
hi("Janet"); // Hello Janet
• let 과 const 로 선언된 변수, 함수들은 블록 레벨 스코프가 된다.
💡 참고로, 함수 레벨 스코프는 블록 레벨 스코프보다 더 넓은 범위를 가지므로 편리하기도 하지만 반대로 코드에 대한 복잡성을 증가시키는 요인이 된다.
function hi(name) {
if (name) {
let greeting = 'Hello ' + name;
}
console.log(greeting);
}
hi('Janet'); // greeting is not defined
null을 반환하게 된다.