실행 컨텍스트 및 호출 스택

DDD
풀어 주다: 2024-09-19 06:32:37
원래의
1089명이 탐색했습니다.

Execution Context & Call Stack

최상위 코드, 즉 fn 내부에 없는 코드에 대한 전역 실행 컨텍스트 생성. 따라서 fn 외부의 코드가 먼저 실행됩니다.
fn-decln/exprsn의 fn 본문 내부 코드는 호출될 때만 실행됩니다.

실행 컨텍스트(EC)

JS 조각이 실행되는 환경
지역 변수, fn에 전달된 args처럼 일부 코드가 실행되는 데 필요한 모든 정보를 저장합니다.
JS 코드는 항상 EC 내부에서 실행됩니다.
JS 프로젝트 규모에 관계없이 정확히 하나의 글로벌 EC입니다.
fn 내부에 없는 코드에 대해 생성된 기본 컨텍스트입니다.
그런 다음 코드는 전역 EC 내부에서 실행됩니다
최상위 코드 실행 후 fns 실행 및 C/bs 대기
각 fn 호출에 대해 해당 fn을 실행하기 위해 새 EC가 생성됩니다. 메서드도 개체에 연결된 fns이므로 마찬가지입니다.
이러한 모든 EC가 함께 호출 스택을 구성합니다.
모든 fns가 실행되면 엔진은 CB가 도착하고 이를 실행하기를 기다립니다. 전. 이벤트 루프에서 제공하는 클릭 이벤트 콜백.

EC 내부에는 무엇이 있나요?

  1. 다음으로 구성된 가변 환경
  2. let, const, var 선언
  3. 기능
  4. arguments 객체: fn에 전달된 모든 args를 EC에 저장합니다.
    각 fn은 호출된 대로 자체 EC를 갖습니다. 그리고 선언된 변수는 변수 환경에서 종료됩니다

  5. 스코프 체인:
    Fns는 범위 체인을 사용하여 fns 외부 변수에 액세스할 수 있습니다.
    현재 fn 외부에 있는 변수에 대한 참조를 포함하고 범위 체인을 추적하기 위해 각 EC에 저장됩니다.

  6. 각 EC도 'this' 키워드를 받습니다.

위의 세 가지 모두 실행 직전인 '생성 단계'에서 생성됩니다. 이는 최상위 레벨에서 코드를 실행하는 데 필요한 것입니다.

화살표 fns EC의 경우:

우리는 인수 객체, 이 키워드를 갖지 않을 것입니다. Arrow fns는 위의 두 fn 중 가장 가까운 일반 fn을 사용합니다.

인수: 객체와 같은 배열로, 화살표 fn이 아닌 일반 fn에 전달된 모든 인수를 포함합니다.

호출 스택 메모리 힙 = JS 엔진

호출 스택

실행 중인 위치를 추적하기 위해 EC가 서로 쌓이는 위치입니다. 최상위 EC는 우리가 실행하고 있는 EC입니다. 실행이 끝나면 스택 상단에서 제거되고 제어권은 기본 EC로 전송됩니다.
중첩된 fn 호출이 있는 경우 JS에는 실행 스레드가 하나만 있으므로 호출 스택에서 내부 fn 실행 결과를 반환하기 위해 외부 fn 호출이 일시 중지됩니다. 이제 이전 EC가 활성 EC가 됩니다
그런 다음 최상위 EC가 반환되면서 호출 스택에서 팝됩니다.
호출 스택에서 가장 낮은 것은 전역 EC이고, 맨 위에는 순서대로 발생하는 fn 호출이 있습니다.
실행 순서가 손실되지 않도록 보장합니다.
결국 프로그램은 종료되고 글로벌 EC도 콜스택에서 튀어나오게 됩니다.

JS 코드는 호출 스택에 있는 EC 내부에서 실행됩니다.

Hence, we can say that each EC has:
1. Variable environment
2. Scope chain
3. 'this' keyword
로그인 후 복사

범위 지정

JS 엔진이 프로그램 변수를 구성하고 액세스하는 방법
변수는 어디에 살고 있나요
특정 변수에 액세스할 수 있는 곳과 액세스할 수 없는 곳은 어디인가요?

어휘 범위 지정:

JS에는 코드 내 fns 및 블록 배치에 따라 범위 지정이 제어되는 Leical 범위 지정이 있습니다.
전. 중첩된 fn은 상위 fn의 변수에 액세스할 수 있습니다.

범위:

특정 변수가 선언된 공간이나 환경(fns의 경우 변수 환경). fns EC에 저장되는 변수 env입니다.
fns의 경우 Var env와 범위는 모두 동일합니다.

Three scopes in JS are:
1. Global scope
2. Fn scope
3. Block scope [ES6]
로그인 후 복사

스코프(Scope)는 변수가 선언되는 곳입니다. 따라서 fns는 변수에 저장된 값일 뿐이므로 Fns에도 해당됩니다.

변수의 범위

특정 변수에 접근할 수 있는 코드 영역

범위는 변수의 범위와 미묘한 차이가 있습니다.

## Global Scope:
For top level code
For variables declared outside of any fn or block which are accessible from everywhere
Variables in this scope are at the top of scope chain. Hence, can be used by every nested scope.
로그인 후 복사
## Fn Scope:
Each fn has creates its own scope
Variables are accessible ONLY inside fn, NOT outside. Else Reference Error
Also called local scope
Fn decln, exprsn, arrow all three create their own scopes.
Only way to create scope using ES5 which had only fn & global scope.
로그인 후 복사
## Block Scope:
Introduced in ES6, not only fn but {} also create a scope known as block scope which work only for ES6 variables i.e let-const types. DOesn't work for variables declared with 'var' as its fn scoped.
Variables accessible only inside block i.e {} 
This only applies to variables declared with let-const only.
Fns are also block scoped in ES6 (only in strict mode, should be used)
variables declared using 'var' will be accessible outside the block
Scoped to the current fn or the global scope.
var variables only care about fn, they ignore blocks. They end up in nearest fn scope.
로그인 후 복사

모든 중첩 범위는 외부 범위 및 전역 범위의 변수에 액세스할 수 있습니다. fn 인수에도 동일하게 적용됩니다.

fn이 해당 범위에서 변수를 찾지 못하면 범위 체인을 조회하여 외부 범위에 있는 변수를 찾습니다. 이 프로세스를 범위 체인의 변수 조회라고 합니다. 이는 반대 방향으로는 작동하지 않습니다. 즉, fn 또는 외부 범위 외부에서 중첩된 fn 변수 또는 범위에 액세스할 수 없습니다.
형제 범위는 서로의 변수에 액세스할 수 없습니다
가장 안쪽 범위만 외부 범위에 액세스할 수 있으며 그 반대 범위에는 액세스할 수 없습니다.

fn이 호출되는 정확한 순서로 각 fn에 대한 하나의 EC는 EC 내부의 변수와 함께 호출 스택에 배치됩니다. Global EC는 Call Stack의 최하위에 위치합니다

Scope chain:
Its all about the order in which fns are written in the code.
Has nothing to do with order in which fns were called.
Scope chain gets the variable environment from the EC.
Order of fn calls is not relevant to the scope chain at all.

const a = 'Alice';
first();

function first(){
  const b = "Hello";
  second();

  function second(){
    const c = "Hi";
    third();
  }
}

function third(){
  const d = "Hey";
  console.log(d + c + b + a); // Reference Error
}

## Call Stack order:
third() EC - top
second() EC
first() EC
global EC - bottom


Scope Chain:
second() --nested inside--> first() --nested inside--> global scope.
third() is independently defined inside gloabal scope.

Reference Error occurred because both 'c' as well as 'b' cannot be accessed using the scope chain.
로그인 후 복사

Summary:
E-C, Var Env, Cl-Sk, Scope, Scope-chain are all different but related concepts.
Scoping asks the questions where do variables live, where can we access the variables and where not.
Lexical Scoping in JS: Rules of where we can access variables are based exactly where in the code fns and blocks are written.
Every scope has access to all the variables from all its outer scopes. This is scope chain which is a one-way street. An outer scope can never access variables of inner scope.
Scope chain of a certain scope is equal to adding together all the Var Envs of all the parent scopes.
Scope chain has nothing to do with the order in which fns are called. It does not affect the scope chain at all.
When a variable is not found in current scope, engine looks up the scope chain until it finds the variable its looking for. This is called variable look-up.

위 내용은 실행 컨텍스트 및 호출 스택의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!