
1. 스코프란?
`스코프(scope)`란 변수에 접근할 수 있는 위치를 제어한다.
`전역 스코프(global scope)`를 가지는 변수는 코드의 어느 곳에서나 접근할 수 있다.
`블록 스코프(block scope)`를 가지는 변수는 변수가 선언된 블럭 내부에서만 접근 가능하다.
여기서 `블록(block)`은 함수, 루프, 혹은 중괄호({})로 구분되는 모든 영역을 뜻한다.
1-1. var
var myInt = 1;
if (myInt === 1) {
var mySecondInt = 2;
console.log(mySecondInt);
// 2
}
console.log(mySecondInt);
// 2
var 키워드로 선언된 변수 myInt 는 블럭 스코프를 가지지 않기 때문에 블록 외부에서도 그 값에 접근할 수 있다.
1-2. let
let myInt = 1;
if (myInt === 1) {
let mySecondInt = 2;
console.log(myInt);
//2
}
console.log(mySecondInt);
// Uncaught ReferenceError: mySecondInt is not defined
반면 블록 스코프 외부에서 변수에 접근 할 수 없으며, 접근을 시도하면 에러가 난다.
`let` 또는 `const` 키워드로 선언된 변수는 변수가 선언된 위치에 해당하는 블록 스코프를 가지게 된다.
2. this 키워드
this는 현재 실행 중인 함수가 속한 객체를 참조한다.
this의 값은 함수가 호출되는 방식에 따라 달라진다는 중요한 특성이 있다.
2-1. 객체의 메서드로 호출된 경우
const myCar = {
color: 'grey',
logColor: function() {
console.log(this.color);
}
};
myCar.logColor(); // 출력: "grey"
이 예시에서 myCar.logColor()를 호출하면 this는 myCar 객체 자신을 참조한다.
`this.color` → "grey"
2-2. 일반 함수로 this를 호출한 경우
⚠️ 만약 logColor를 따로 꺼내서 호출하면?
const log = myCar.logColor;
log(); // this는 undefined 또는 window, 결과는 undefined
→ 일반 함수 호출이 되어 this가 바뀌므로 조심해야 한다.
function logThis() {
console.log(this);
}
logThis(); // 브라우저 환경에서는 window { ... }
왜 this가 window인가? logThis()는 일반 함수 호출이다. 이 때의 this는 전역 객체를 참조하기 때문에
- 브라우저에서는 → window
- Node.js에서는 → global (strict mode에선 undefined)
가 각각 호출된다.
2-3. strict mode
이럴 때 스트릭트 모드(strict mode)를 설정하면 실수로 Window 객체를 참조하는 것을 방지할 수 있다.
스트릭트 모드를 설정하려면 아래와 같이 자바스크립트 파일의 시작 부분에 'use strict'; 를 삽입하면 된다.
'use strict';
function logThis() {
console.log(this);
}
logThis(); // 출력: undefined
말 그대로 strict mode의 엄격한 규칙 중에는 전역 객체의 값을 Window 객체 대신 undefined로 설정하는 규칙이 있어서 전역 범위로 정의된 this 키워드의 값도 undefined가 된다.
| 호출 방식 | this가 가리키는 값 |
| 일반 함수 호출 | `window` (또는 `global`) |
| strict 모드 + 일반 함수 | `undefined` |
| 객체의 메서드 호출 | 그 객체 자신 |
| 화살표 함수 | 선언 시의 `this`를 상속 |
3. bind()
this 값을 수동으로 설정하고자 할 때 사용하는 것이 `.bind()`이다.
bind()는 함수의 this 값을 고정시킨 새로운 함수를 반환한다.
const myCar = {
color: "red"
};
function showColor() {
console.log(this.color);
}
const boundShowColor = showColor.bind(myCar); // this 고정됨
const unboundShowColor = showColor; // this 고정 안 됨
boundShowColor(); // 출력: red (this는 myCar)
unboundShowColor(); // 출력: undefined (this는 전역 객체 or undefined)
4. call()
call()은 함수를 즉시 실행하면서 this를 myCar로 설정한다.
const myCar = {
color: "blue"
};
function printColor() {
console.log(this.color);
}
printColor.call(myCar); // 출력: blue
5. 화살표 함수
arrowFn은 화살표 함수이므로 자신의 this를 만들지 않고, logColor의 this인 myCar를 그대로 사용한다.
const myCar = {
color: "green",
logColor: function () {
const arrowFn = () => {
console.log(this.color);
};
arrowFn(); // 화살표 함수: 바깥 this(myCar)를 그대로 사용
}
};
myCar.logColor(); // 출력: green
⚠️ 만약 일반 함수였다면
const myCar = {
color: "yellow",
logColor: function () {
function innerFn() {
console.log(this.color);
}
innerFn(); // 일반 함수: 전역 this 사용 → undefined (strict 모드)
}
};
myCar.logColor(); // 출력: undefined (또는 window.color)
'JavaScript' 카테고리의 다른 글
| [JavaScript] 자바스크립트의 map() (2) | 2025.06.24 |
|---|---|
| [JavaScript] 자바스크립트 이벤트, 이벤트 핸들러, 버블링과 캡처링 등 총정리 (11) | 2025.02.08 |
| [JavaScript] 자바스크립트 제이쿼리 (jQuery) 위치 탐색선택자, 속성 탐색 선택자, 배열 관련 메서드 정리 (20) | 2025.02.08 |
| [JavaScript] 자바스크립트 제이쿼리 (jQuery) 기본선택자에 대해 알아보자! (10) | 2025.02.07 |
| [JavaScript] jQuery를 사용할 때 유의해야 할 사항들 (8) | 2025.02.05 |