https://meetup.toast.com/posts/129
https://poiemaweb.com/es6-block-scopeA. Execution Context๋?
์คํ ๊ฐ๋ฅํ ์ฝ๋๋ฅผ ํ์ํํ๊ณ ๊ตฌ๋ถํ๋ ์ถ์์ ์ธ ๊ฐ๋ ์ด๋ผ๊ณ ์ ์ํ๋ค. ์ข ๋ ์ฝ๊ฒ ๋งํ์๋ฉด ์คํ ์ปจํ ์คํธ๋ ์คํ ๊ฐ๋ฅํ ์ฝ๋๊ฐ ์คํ๋๊ธฐ ์ํด ํ์ํ ํ๊ฒฝ
poiemaweb ์คํ ์ปจํ ์คํธ์ ์๋ฐ์คํฌ๋ฆฝํธ์ ๋์ ์๋ฆฌ
๊ฐ๊ฐ์ ๋จ์๋ง๋ค Execution Context๋ฅผ ์์ฑํ๋๋ฐ, ์ด ๋ ์ด๊ธฐํ(Initalizing) ํ๋ ๋ฐฉ์์ด ๋ค๋ฆ ๋๋ค.
Javascript ์์ง์ด ์์ค ์ฝ๋๋ฅผ ํ๊ฐํ ๋ ์์ฑ๋ฉ๋๋ค.
ExecutionContext = {
// ์ต์ด ์์ฑ๋ ์์ ์๋ LexicalEnvironment === VariableEnvironment
LexicalEnvironment: LexicalEnvironment,
VariableEnvironment: LexicalEnvironment,
outer: outer Execution Context
}
const foo = (ninkName) => {
const name = 'bob';
const age = 20;
const bar = () => {}
return bar;
}
foo(1); // foo ํจ์๋ฅผ ํธ์ถํ๋ฉด ์์ง์ด foo์ EC๋ฅผ ์์ฑ ๋ฐ ์ด๊ธฐํ ํฉ๋๋ค.
// foo Function Execution Context
ExecutionContext: {
LexicalEnvironment: {
environmentRecord: {
ninkName: 1,
bar: Function Object
name: "bob",
age: 20,
}
},
variableEnvironemt: LexicalEnvironment,
outer: global EC
}
environmentRecord๋ ์๋ณ์/๊ฐ ๋ชจ์์
๋๋ค.
Javascript ์์ง์ด environmentRecord๋ฅผ ์ด๊ธฐํ ํ ๋ ์์๊ฐ ์กด์ฌํฉ๋๋ค.
1. ๋งค๊ฐ ๋ณ์ ์๋ณ์ ์ ์ธ ๋ฐ ๊ฐ ํ ๋น
2. function statement ์๋ณ์ ์ ์ธ ๋ฐ ๊ฐ ํ ๋น
3. function expression ์๋ณ์ ์ ์ธ
4. ๋ณ์ ์๋ณ์ ์ ์ธ
1. ๋ณ์, ํจ์ ์๋ณ์ ๊ฐ ํ ๋น
var ํค์๋๋ก ๋ณ์๋ฅผ ์ ์ธํ ๊ฒฝ์ฐ ์๋ณ์์ ๋ฑ๋ก๊ณผ ํจ๊ป ๋ฉ๋ชจ๋ฆฌ ๊ณต๊ฐ์ ํ๋ณดํ๊ณ , undefined๋ก ์ด๊ธฐํ ๋๋ ๋ฐ๋ฉด,
let/const ํค์๋๋ก ๋ณ์๋ฅผ ์ ์ธํ ๊ฒฝ์ฐ ์๋ณ์๋ง record์ ๋ฑ๋ก ๋๊ณ , ํด๋น ์ฝ๋๊ฐ ์คํ๋ ๋ ์ด๊ธฐํ์ ํจ๊ป ๊ฐ์ด ํ ๋น๋จ์ผ๋ก ์ธํด, ์คํ ๋๊ธฐ์ ์๋ ์๋ณ์๋ฅผ ์ฐธ์กฐํ ์ ์๋ค.
outer ํ๋กํผํฐ๋ ํ์ฌ Execution Context๋ฅผ ์์ฑํด๋ธ Execution Context๋ฅผ ์ฐธ์กฐํฉ๋๋ค.
ํ์ฌ EC๊ฐ ์์ฑํด๋ธ EC ๋ฐ์ดํฐ๋ [[Scopes]] ๋ผ๋ ๋ด๋ถ ๋ฉ์๋(Internal Method)์ ๋ด๊ฒจ์ ธ ์์ต๋๋ค.
const foo = () => {}
console.dir(foo);
์ถ๋ ฅ
foo ํจ์์ EC์ outer ํ๋กํผํฐ๋ [[Scopes]] ๋ฅผ ์ฐธ๊ณ ํ์ฌ Global EC๋ก ๋ฐ์ธ๋ฉ ํฉ๋๋ค.
๊ทธ๋ฆฌ๊ณ ์ด outer ํ๋กํผํฐ๋ก ์ค์ฒฉ๋ Context์์ ์๋ณ์๋ฅผ ์ฐพ์๋
๋๋ค.
์ด๋ฅผ ์๋์ ๊ฐ์ด ๋ช
์นญํฉ๋๋ค.
ES3 : List ๊ตฌ์กฐ๋ก ์ค์ฒฉ๋ EC์ ์ฐธ์กฐ๋ฅผ ๊ด๋ฆฌํจ.
ES6 : outer ํ๋กํผํฐ๋ก ์ง์ ํ์ฌ EC์ ์์ EC๋ฅผ ์ฐธ์กฐํจ.
const globalName = 'Global';
const foo = () => {
const name = 'foo';
const inner = () => {
consoleo.log(name, globalName);
}
inner();
}
foo();
// ES3 scope chain
// ์ค์ฒฉ๋ Scope๋ฅผ ๋ฆฌ์คํธ ํํ๋ก ์ฌ์ฉ
0 - inner Function EC // name ์๋ณ์๋ฅผ ์ฐพ์๋ ํ์ฌ ์ปจํ
์คํธ์ ์์ผ๋ฉด ๋ฆฌ์คํธ๋ฅผ ํ๊ณ ์ฌ๋ผ๊ฐ.
1 - foo Function EC
2 - global EC
// ES6 scope chain
inner Function EC: {
environment record: {/* ์๋ณ์: ๊ฐ */},
outer: foo execution context, // inner ํจ์ ๊ฐ์ฒด๋ foo ์์ ์์ฑ
}
foo Function EC: {
environment record: {/* ์๋ณ์: ๊ฐ */},
outer: global execution context, // foo ํจ์ ๊ฐ์ฒด๋ global ์์ ์์ฑ
}
global EC: {
environment record: {/* ์๋ณ์: ๊ฐ */},
outer: null,
}
๐๐์ถ๊ฐ๋ก ์ ๋ฐ์ดํธ ํ๊ฒ ์ต๋๋ค..๐๐