Execution Context
1. Execution Context란?
2. 자바스크립트 코드 실행에 필요한 정보
- 변수
- 함수
- 변수의 유효범위
- this
3. Types of Execution Context 실행 컨텍스트 타입
- Global Execution Context 전역 실행 컨텍스트
window 전역컨텍스트 생성, this를 전역 객체로 설정 - Functional Execution Context 함수 실행 컨텍스트
함수가 호출될 때마다 해당 함수에 대한 새로운 실행 컨텍스트가 생성된다. 여러개를 호출하면 순차적으로 호출된다. - **Eval Function Execution Context Eval 실행 컨텍스트
4. Execution Stack
LIFO (Last In First Out) 구조형태
javascript 엔진은 실행컨텍스트가 맨위에 있는 함수를 실행한 뒤, 함수가 종료되면 스택에서 제거한 뒤 호출 스택은 최신화된 스택에서 맨위의 컨텍스트를 이전과 동일한 로직으로 접근한다.
let global = 'global Execute'; // 1. global execution context
function second() {
console.log('second') // 3. second function execution context
}
function first() {
console.log('first') // 2. first function execution context
second(); //두번째 함수 실행
}
first();
보면 전역컨텍스트를 처음부터 끝까지 스택에 쌓여 있으며, 함수 실행 시마다 새로운 실행 컨텍스트가 생성된다. 그리고 해당 함수 안에 있는 모든 변수, 함수가 종료될 때까지 해당 함수는 스택에서 쌓여있는 것을 확인할 수 있다.
5. Execution Context 생성로직
Creation Phase 변수와 해당 변수에 대입된 값 매핑하는 곳 !
- Lexical Environment
- Environment Record
= 함수와 변수 선언을 저장하는 곳 - Reference to the outer environment
= 외부환경에 대한 참조 (Lexical Environment 에서 찾지 못했다면 외부환경에서 해당 변수를 찾아봄) - This binding
여기서 this의 값 할당이 결정된다.
전역 실행 컨텍스트에서 this는 전역객체이다.const person = { name: 'joanna', age: 30, getAge() { console.log(`age: ${this.age}`) } }; /** * 1. 여기서의 this는 person 객체를 참조하고 있기 떄문에 person 객체 자신이 된다. * * this: person * this.age: 30 */ person.getAge(); //age: 30 /** * 2. 객체를 복제했기 때문에 새로운 객체가 형성되었고, 해당 객체를 바라보기 된다. * * this: copyObj * this.age: 20 */ const copyObj = person; copyObj.age = 20; copyObj.getAge(); //age: 20 /** * 3. 여기서는 객체 안의 함수를 복제했으므로 person객체를 참조하고 있다고 볼 수 없다. * 따라서 this는 전역 객체가 되고, 전역 객체에는 age가 없기 때문에 undefined가 된다. * * this: window * this.age: undefined */ const copyFunction = person.getAge; copyFunction(); //age: undefined
- window 함수 실행 컨텍스트에서의 값은 this 함수가 호출되는 방식에 따라 다르다.
객체 참조에 의해서 호출될 경우에는 해당 객체가 this가 되고,
그렇지 않을 경우 window가 this가 되며,
strict mode에서는 undefined가 된다.
- Environment Record
- Variable Environment
Environment Records(함수와 변수 선언을 저장하는 곳)에 바인딩 된것들이 Lexical Environment라면, Variable Environment 또한 Lexical Environment이고, Lexical Environment의 모든 프로퍼티와 요소를 가진다.
여기서는 var 변수만 저장하고 let, const는 Lexical Environment에서 저장한다.
Excution Phase
모든 변수에 대한 값 할당이 완료되고 코드가 최종적으로 실행되는곳
<실제 예시>
작성한 코드
let a = 20; //lexical
const b = 30; //lexical
var c; //variable
function multiply(e, f){ //lexical
var g = 20;
return e * f * g;
}
c = multiply(20, 30); //이거 실행할 때 함수 실행 컨텍스트 생성, 끝나면 삭제
1. 전역 실행 컨텍스트 생성 (a, b, c, multiply)
GlobalExecutionContext = {
LexicalEnvironment: {
EnvironmentRecord: {
Type: "Object",
//Identifier bindings go here
a: 20,
b: 30,
multiply: < func >
}
outer: <null>
ThisBinding: <Global Object>
},
VariableEnvironment: {
EnvironmentRecord: {
Type: "Object",
// Identifier bindings go here
c: undefined,
}
outer: <null>
ThisBinding: <Global object>
}
}
2. 함수 실행시에 새로운 함수 실행 컨텍스트 생성
FUnctionExecutionContext = {
LexicalEnvironment: {
EnvironmentRecord: {
Type: "Declarative",
//Identifier bindings go here
Arguments: {0: 20, 1: 30, length: 2},
},
outer: <GlobalLexicalEnvironment>,
ThisBinding: <Global Object or undefined>,
},
VariableEnvironment: {
EnvironmentRecord: {
Type: "Declarative",
//Identifier bindings go here
g: 20 // 처음에 undefined로 생성되고, 20 값 할당
},
outer: <GlobalLexicalEnvironment>,
ThisBinding: <Global Object or undefined>
}
}
3. 전역 실행 컨텍스트 업데이트
GlobalExecutionContext = {
// ...
VariableEnvironment: {
EnvironmentRecord: {
Type: "Object",
// Identifier bindings go here
c: 1200, // 20 * 30 * 20
}
outer: <null>
ThisBinding: <Global object>
}
}
4. 함수 실행 컨텍스트였던 FUnctionExecutionContext 삭제되고 전역만 남음
(아래 이미지 마지막단계)
반응형
'프론트엔드' 카테고리의 다른 글
Scope 스코프 (0) | 2022.11.02 |
---|---|
Event Loop 이벤트 루프 (태스크큐 & 마이크로 태스크 큐) (0) | 2022.11.02 |
Javascript 메모리 개념 (V8엔진 & 콜스택Call Stack & 힙Heap) (0) | 2022.11.02 |
http1.1 와 http2 (0) | 2022.11.01 |
브라우저 렌더링 (0) | 2022.09.29 |