diff --git a/1-js/06-advanced-functions/03-closure/10-make-army/task.md b/1-js/06-advanced-functions/03-closure/10-make-army/task.md index 1ce14d497b..ac37057c29 100644 --- a/1-js/06-advanced-functions/03-closure/10-make-army/task.md +++ b/1-js/06-advanced-functions/03-closure/10-make-army/task.md @@ -14,42 +14,26 @@ function makeArmy() { let i = 0; while (i < 10) { -<<<<<<< HEAD let shooter = function() { // shooter 함수 alert( i ); // 몇 번째 shooter인지 출력해줘야 함 -======= - let shooter = function() { // create a shooter function, - alert( i ); // that should show its number ->>>>>>> upstream/master }; - shooters.push(shooter); // and add it to the array + shooters.push(shooter); // shooters 배열에 shooter 함수 추가 i++; } - // ...and return the array of shooters + // shooters 반환 return shooters; } let army = makeArmy(); -<<<<<<< HEAD army[0](); // 0번째 shooter가 10을 출력함 -army[5](); // 5번째 shooter 역시 10을 출력함 +army[1](); // 1번째 shooter가 10을 출력함 +army[2](); // 2번째 shooter 역시 10을 출력함 // 모든 shooter가 자신의 번호 대신 10을 출력하고 있음 ``` -왜 모든 shooter가 동일한 숫자를 출력하는 걸까요? 제대로 된 번호가 출력될 수 있게 코드를 수정해 보세요. -======= -*!* -// all shooters show 10 instead of their numbers 0, 1, 2, 3... -army[0](); // 10 from the shooter number 0 -army[1](); // 10 from the shooter number 1 -army[2](); // 10 ...and so on. -*/!* -``` - -Why do all of the shooters show the same value? +왜 모든 shooter가 동일한 숫자를 출력하는 걸까요? -Fix the code so that they work as intended. ->>>>>>> upstream/master +제대로 된 번호가 출력될 수 있게 코드를 수정해 보세요. diff --git a/1-js/06-advanced-functions/03-closure/5-function-in-if/task.md b/1-js/06-advanced-functions/03-closure/5-function-in-if/task.md index 9b255dc38f..cd10caa28b 100644 --- a/1-js/06-advanced-functions/03-closure/5-function-in-if/task.md +++ b/1-js/06-advanced-functions/03-closure/5-function-in-if/task.md @@ -1,11 +1,6 @@ importance: 5 -<<<<<<< HEAD # if 문 안의 함수 -======= ---- -# Function in if ->>>>>>> upstream/master 아래 예시의 실행 결과를 예측해보세요. diff --git a/1-js/06-advanced-functions/03-closure/7-let-scope/solution.md b/1-js/06-advanced-functions/03-closure/7-let-scope/solution.md index 490d8ec50b..7ff607f201 100644 --- a/1-js/06-advanced-functions/03-closure/7-let-scope/solution.md +++ b/1-js/06-advanced-functions/03-closure/7-let-scope/solution.md @@ -26,15 +26,9 @@ func(); ```js function func() { *!* -<<<<<<< HEAD // 엔진은 함수가 시작될 때 로컬 변수 x의 존재를 알고 있지만 // let 문이 실행될 때까지 x는 '초기화되지 않은' 상태(dead zone)이기 때문에 // 에러가 발생합니다. -======= - // the local variable x is known to the engine from the beginning of the function, - // but "uninitialized" (unusable) until let ("dead zone") - // hence the error ->>>>>>> upstream/master */!* console.log(x); // ReferenceError: Cannot access 'x' before initialization diff --git a/1-js/06-advanced-functions/03-closure/article.md b/1-js/06-advanced-functions/03-closure/article.md index 5e9d7aefe1..d4f9caa2a5 100644 --- a/1-js/06-advanced-functions/03-closure/article.md +++ b/1-js/06-advanced-functions/03-closure/article.md @@ -7,11 +7,7 @@ 그런데 함수가 생성된 이후에 외부 변수가 변경되면 어떤 일이 발생할까요? 함수는 새로운 값을 가져올까요? 아니면 생성 시점 이전의 값을 가져올까요? -<<<<<<< HEAD 매개변수를 통해 함수를 넘기고 이 함수를 저 멀리 떨어진 코드에서 호출할 땐 어떤 일이 발생할까요? 함수는 호출되는 곳을 기준으로 외부 변수에 접근할까요? -======= -And what if a function is passed along as an argument and called from another place of code, will it get access to outer variables at the new place? ->>>>>>> upstream/master 이젠 이런 간단한 시나리오부터 시작해 좀 더 복잡한 시나리오를 다룰 수 있도록 지식을 확장해 봅시다. @@ -150,11 +146,7 @@ alert( counter() ); // 2 그런데 `makeCounter`를 살펴보다 보면 "`counter`를 여러 개 만들었을 때, 이 함수들은 서로 독립적일까? 함수와 중첩 함수 내 `count` 변수엔 어떤 값이 할당될까?" 같은 의문이 들기 마련입니다. -<<<<<<< HEAD 이런 의문을 해결할 수 있게 되면 자바스크립트 숙련도가 크게 올라갑니다. 좀 더 복잡한 시나리오도 다룰 수 있게 되죠. 자, 긴말할 필요 없이 바로 시작해봅시다. -======= -Understanding such things is great for the overall knowledge of JavaScript and beneficial for more complex scenarios. So let's go a bit in-depth. ->>>>>>> upstream/master ## 렉시컬 환경 @@ -322,11 +314,7 @@ let counter = makeCounter(); 함수 호출이 끝나면 함수에 대응하는 렉시컬 환경이 메모리에서 제거됩니다. 함수와 관련된 변수들은 이때 모두 사라지죠. 함수 호출이 끝나면 관련 변수를 참조할 수 없는 이유가 바로 여기에 있습니다. 자바스크립트에서 모든 객체는 도달 가능한 상태일 때만 메모리에 유지됩니다. -<<<<<<< HEAD 그런데 호출이 끝난 후에도 여전히 도달 가능한 중첩 함수가 있을 수 있습니다. 이때는 이 중첩함수의 `[[Environment]]` 프로퍼티에 외부 함수 렉시컬 환경에 대한 정보가 저장됩니다. 도달 가능한 상태가 되는 것이죠. -======= -However, if there's a nested function that is still reachable after the end of a function, then it has `[[Environment]]` property that references the lexical environment. ->>>>>>> upstream/master 함수 호출은 끝났지만 렉시컬 환경이 메모리에 유지되는 이유는 바로 이 때문입니다. @@ -345,11 +333,7 @@ let g = f(); // g.[[Environment]]에 f() 호출 시 만들어지는 // 렉시컬 환경 정보가 저장됩니다. ``` -<<<<<<< HEAD -그런데 이렇게 중첩함수를 사용할 때는 주의할 점이 있습니다. `f()`를 여러 번 호출하고 그 결과를 어딘가에 저장하는 경우, 호출 시 만들어지는 각 렉시컬 환경 모두가 메모리에 유지된다는 점입니다. 아래 예시를 실행하면 3개의 렉시컬 환경이 만들어지는데, 각 렉시컬 환경은 메모리에서 삭제되지 않습니다. -======= -Please note that if `f()` is called many times, and resulting functions are saved, then all corresponding Lexical Environment objects will also be retained in memory. In the code below, all 3 of them: ->>>>>>> upstream/master +그런데 이렇게 중첩 함수를 사용할 때는 주의할 점이 있습니다. `f()`를 여러 번 호출하고 그 결과를 어딘가에 저장하는 경우, 호출 시 만들어지는 각 렉시컬 환경 모두가 메모리에 유지된다는 점입니다. 아래 예시를 실행하면 3개의 렉시컬 환경이 만들어지는데, 각 렉시컬 환경은 메모리에서 삭제되지 않습니다. ```js function f() { @@ -387,11 +371,7 @@ g = null; // 도달할 수 없는 상태가 되었으므로 메모리에서 삭 그러나 실제로는 자바스크립트 엔진이 이를 지속해서 최적화합니다. 자바스크립트 엔진은 변수 사용을 분석하고 외부 변수가 사용되지 않는다고 판단되면 이를 메모리에서 제거합니다. -<<<<<<< HEAD **디버깅 시, 최적화 과정에서 제거된 변수를 사용할 수 없다는 점은 V8 엔진(Chrome, Edge, Opera에서 쓰임)의 주요 부작용입니다.** -======= -**An important side effect in V8 (Chrome, Edge, Opera) is that such variable will become unavailable in debugging.** ->>>>>>> upstream/master Chrome 브라우저에서 개발자 도구를 열고 아래의 코드를 실행해봅시다. @@ -433,12 +413,6 @@ let g = f(); g(); ``` -<<<<<<< HEAD 이런 V8만의 부작용을 미리 알아 놓는 것이 좋습니다. Chrome이나 Edge, Opera에서 디버깅하는 경우라면 언젠간 이 이슈를 만나게 될 테니까요. 이 부작용은 버그라기보다는 V8만의 특별한 기능이라고 생각하시면 될 것 같습니다. 미래에 이 기능은 변경될 수 있습니다. 최적화 과정에서 외부 변수가 어떻게 처리되었는지 확인하고 싶다면 이 페이지로 돌아오셔서 예시를 실행해 보세요. -======= -This feature of V8 is good to know. If you are debugging with Chrome/Edge/Opera, sooner or later you will meet it. - -That is not a bug in the debugger, but rather a special feature of V8. Perhaps it will be changed sometime. You can always check for it by running the examples on this page. ->>>>>>> upstream/master diff --git a/1-js/06-advanced-functions/04-var/article.md b/1-js/06-advanced-functions/04-var/article.md index 74adb83aab..cb2cbf5b28 100644 --- a/1-js/06-advanced-functions/04-var/article.md +++ b/1-js/06-advanced-functions/04-var/article.md @@ -4,11 +4,7 @@ ```smart header="오래된 스크립트를 읽는 데 도움을 주는 글입니다." 이번 주제에선 작성된 지 오래된 스크립트를 읽는 데 도움을 줄 만한 내용을 다룹니다. -<<<<<<< HEAD 새로운 코드를 작성할 때는 이 방법을 쓰시면 안 됩니다. -======= -That's not how we write new code. ->>>>>>> upstream/master ``` [변수](info:variables)를 다룬 첫 번째 장에서 변수 선언 방법 세 가지를 배운 바 있습니다. @@ -32,11 +28,7 @@ alert(message); // 안녕하세요. ## var는 블록 스코프가 없습니다. -<<<<<<< HEAD `var`로 선언한 변수의 스코프는 함수 스코프이거나 전역 스코프입니다. 블록 기준으로 스코프가 생기지 않기 때문에 블록 밖에서 접근 가능합니다. -======= -Variables, declared with `var`, are either function-scoped or global-scoped. They are visible through blocks. ->>>>>>> upstream/master 예시: @@ -73,12 +65,8 @@ for (var i = 0; i < 10; i++) { } *!* -<<<<<<< HEAD alert(i); // 10, 반복문이 종료되었지만 'i'는 전역 변수이므로 여전히 접근 가능합니다. -======= -alert(i); // 10, "i" is visible after loop, it's a global variable -alert(one); // 1, "one" is visible after loop, it's a global variable ->>>>>>> upstream/master +alert(one); // 1, 반복문이 종료되었지만 'one'도 전역 변수이므로 여전히 접근 가능합니다. */!* ``` @@ -94,17 +82,10 @@ function sayHi() { } sayHi(); -<<<<<<< HEAD -alert(phrase); // Error: phrase is not defined -``` - -위에서 살펴본 바와 같이, `var`는 `if`, `for` 등의 코드 블록을 관통합니다. 아주 오래전의 자바스크립트에선 블록 수준 렉시컬 환경이 만들어 지지 않았기 때문입니다. `var`는 구식 자바스크립트의 잔재이죠. -======= alert(phrase); // ReferenceError: phrase is not defined ``` -As we can see, `var` pierces through `if`, `for` or other code blocks. That's because a long time ago in JavaScript, blocks had no Lexical Environments, and `var` is a remnant of that. ->>>>>>> upstream/master +위에서 살펴본 바와 같이, `var`는 `if`, `for` 등의 코드 블록을 관통합니다. 아주 오래전의 자바스크립트에선 블록 수준 렉시컬 환경이 만들어 지지 않았기 때문입니다. `var`는 구식 자바스크립트의 잔재이죠. ## var는 변수의 중복 선언을 허용합니다 @@ -224,19 +205,11 @@ sayHi(); 이처럼 모든 `var` 선언은 함수 시작 시 처리되기 때문에, `var`로 선언한 변수는 어디서든 참조할 수 있습니다. 하지만 변수에 무언가를 할당하기 전까진 값이 undefined이죠. -<<<<<<< HEAD 바로 위의 두 예시에서 `alert`를 호출하기 전에 변수 `phrase`는 선언이 끝난 상태이기 때문에 에러 없이 얼럿 창이 뜹니다. 그러나 값이 할당되기 전이기 때문에 얼럿 창엔 `undefined`가 출력되죠. ### 즉시 실행 함수 표현식 과거엔 `var`만 사용할 수 있었습니다. 그런데 `var`의 스코프는 블록 레벨 수준이 아니죠. 개발자들은 `var`도 블록 레벨 스코프를 가질 수 있게 여러가지 방안을 고려하게 됩니다. 이때 만들어진 것이 '즉시 실행 함수 표현식(immediately-invoked function expressions)'입니다. 즉시 실행 함수 표현식은 `IIFE`라고 부르기도 합니다. -======= -In both examples above, `alert` runs without an error, because the variable `phrase` exists. But its value is not yet assigned, so it shows `undefined`. - -## IIFE - -In the past, as there was only `var`, and it has no block-level visibility, programmers invented a way to emulate it. What they did was called "immediately-invoked function expressions" (abbreviated as IIFE). ->>>>>>> upstream/master 즉시 실행 함수 표현식을 요즘에는 자주 쓰지 않습니다. 하지만 오래된 스크립트에서 만날 수 있기 때문에 즉시 실행 함수 표현식이 무엇인지 알아 둘 필요가 있습니다. @@ -252,23 +225,13 @@ IIFE는 다음과 같이 생겼습니다. })(); ``` -<<<<<<< HEAD 함수 표현식이 만들어지고 바로 호출되면서, 해당 함수가 바로 실행되었습니다. 이 함수는 자신만의 변수를 갖고있네요. 즉시 실행 함수를 만들 땐, 함수 표현식을 괄호로 둘러쌓아 (function {...})와 같은 형태로 만듭니다. 이렇게 괄호로 둘러싸지 않으면 에러가 발생합니다. 자바스크립트는 'function'이라는 키워드를 만나면 함수 선언문이 시작될 것이라 예상합니다. 그런데 함수 선언문으로 함수를 만들 땐 반드시 함수의 이름이 있어야 합니다. 따라서 아래와 예시를 실행하면 에러가 발생합니다. ```js run // 함수를 선언과 동시에 실행하려고 함 -function() { // <-- Error: Function statements require a function name -======= -Here, a Function Expression is created and immediately called. So the code executes right away and has its own private variables. - -The Function Expression is wrapped with parenthesis `(function {...})`, because when JavaScript engine encounters `"function"` in the main code, it understands it as the start of a Function Declaration. But a Function Declaration must have a name, so this kind of code will give an error: - -```js run -// Tries to declare and immediately call a function function() { // <-- SyntaxError: Function statements require a function name ->>>>>>> upstream/master var message = "Hello"; @@ -293,21 +256,12 @@ function go() { ```js run // IIFE를 만드는 방법 -<<<<<<< HEAD (function() { alert("함수를 괄호로 둘러싸기"); }*!*)*/!*(); (function() { alert("전체를 괄호로 둘러싸기"); -======= -*!*(*/!*function() { - alert("Parentheses around the function"); -}*!*)*/!*(); - -*!*(*/!*function() { - alert("Parentheses around the whole thing"); ->>>>>>> upstream/master }()*!*)*/!*; *!*!*/!*function() { @@ -325,13 +279,8 @@ function go() { `var`로 선언한 변수는 `let`이나 `const`로 선언한 변수와 다른 두 가지 주요한 특성을 보입니다. -<<<<<<< HEAD -1. `var`로 선언한 변수는 블록 스코프가 아닌 함수 수준 스코프를 갖습니다. +1. `var`로 선언한 변수는 블록 스코프가 아닌 함수 수준 스코프를 갖습니다. 함수 밖에서 선언한 경우엔 전역 스코프를 갖습니다. 2. `var` 선언은 함수가 시작되는 시점(전역 공간에선 스크립트가 시작되는 시점)에서 처리됩니다. -======= -1. `var` variables have no block scope, their visibility is scoped to current function, or global, if declared outside function. -2. `var` declarations are processed at function start (script start for globals). ->>>>>>> upstream/master 이 외에도 전역 객체와 관련된 특성 하나가 더 있는데, 이에 대해선 다음 챕터에서 다루도록 하겠습니다. diff --git a/1-js/06-advanced-functions/05-global-object/article.md b/1-js/06-advanced-functions/05-global-object/article.md index b8a446ce27..8abfd4a12f 100644 --- a/1-js/06-advanced-functions/05-global-object/article.md +++ b/1-js/06-advanced-functions/05-global-object/article.md @@ -5,11 +5,7 @@ 브라우저 환경에선 전역 객체를 `window`, Node.js 환경에선 `global`라고 부르는데, 각 호스트 환경마다 부르는 이름은 다릅니다. -<<<<<<< HEAD -전역 객체의 이름을 `globalThis`로 표준화하자는 내용이 최근에 자바스크립트 명세에 추가되었기 때문에 모든 호스트 환경이 이를 따라야 하죠. Chromium 기반이 아닌 몇몇 브라우저는 아직 `globalThis`를 지원하진 않지만, 이에 대한 폴리필(polyfill)을 쉽게 만들 수 있습니다. -======= -Recently, `globalThis` was added to the language, as a standardized name for a global object, that should be supported across all environments. It's supported in all major browsers. ->>>>>>> upstream/master +전역 객체의 표준화된 이름으로 `globalThis`가 자바스크립트 명세에 추가되었습니다. 모든 주요 브라우저에서 지원합니다. 본 튜토리얼은 브라우저 환경에서 구동되기 때문에 `window`라는 전역 객체를 사용하도록 하겠습니다. 다른 호스트 환경에서 작업하고 계신다면 `window`대신 `globalThis`를 사용하시면 됩니다. @@ -29,13 +25,9 @@ var gVar = 5; alert(window.gVar); // 5 (var로 선언한 변수는 전역 객체 window의 프로퍼티가 됩니다) ``` -<<<<<<< HEAD -하위 호환성 때문에 이런 방식으로 전역 객체를 사용해도 동작은 하지만, 이 방법은 쓰지 않으시길 바랍니다. [모듈](info:modules)을 사용하는 모던 자바스크립트는 이런 방식을 지원하지 않습니다. -======= -Function declarations have the same effect (statements with `function` keyword in the main code flow, not function expressions). +함수 선언문도 동일하게 동작합니다(함수 표현식이 아닌 메인 코드 흐름의 'function' 키워드를 사용한 문장에 한합니다). -Please don't rely on that! This behavior exists for compatibility reasons. Modern scripts use [JavaScript modules](info:modules) where such a thing doesn't happen. ->>>>>>> upstream/master +하위 호환성 때문에 이런 방식으로 전역 객체를 사용해도 동작은 하지만, 이 방법은 쓰지 않으시길 바랍니다. [모듈](info:modules)을 사용하는 모던 자바스크립트는 이런 방식을 지원하지 않습니다. `var` 대신 `let`을 사용하면 위 예시와는 달리 전역 객체를 통해 변수에 접근할 수 없습니다. @@ -91,14 +83,7 @@ if (!window.Promise) { 전역 객체엔 `Array`와 같은 내장 객체, `window.innerHeight`(뷰포트의 높이를 반환함)같은 브라우저 환경 전용 변수 등이 저장되어 있습니다. - 전역 객체는 `globalThis`라는 보편적인 이름으로 불립니다. -<<<<<<< HEAD - 하지만 '관습'에 따라 브라우저에서는 `window`, Node.js에서는 `global`이라는 이름으로 불릴 때가 많습니다. `globalThis`는 제안 목록에 추가 된 지 얼마 안 된 기능이기 때문에, 비 크로미움 기반 브라우저에선 지원하지 않습니다(폴리필을 구현하면 사용할 수 있습니다). + 하지만 '관습'에 따라 브라우저에서는 `window`, Node.js에서는 `global`이라는 이름으로 불릴 때가 많습니다. - 프로젝트 전체에서 꼭 필요한 변수만 전역 객체에 저장하도록 하고, 전역 변수는 가능한 한 최소한으로 사용합시다. - [모듈](info:modules)을 사용하고 있지 않다면, 브라우저에서 `var`로 선언한 전역 변수는 전역 객체의 프로퍼티가 됩니다. - 이해하기 쉽고 요구사항 변경에 쉽게 대응할 수 있는 코드를 구현하려면, `window.x`처럼 전역 객체의 프로퍼티에 직접 접근합시다. -======= - ...But more often is referred by "old-school" environment-specific names, such as `window` (browser) and `global` (Node.js). -- We should store values in the global object only if they're truly global for our project. And keep their number at minimum. -- In-browser, unless we're using [modules](info:modules), global functions and variables declared with `var` become a property of the global object. -- To make our code future-proof and easier to understand, we should access properties of the global object directly, as `window.x`. ->>>>>>> upstream/master diff --git a/1-js/06-advanced-functions/06-function-object/5-sum-many-brackets/solution.md b/1-js/06-advanced-functions/06-function-object/5-sum-many-brackets/solution.md index cb3aeef838..7fd004e133 100644 --- a/1-js/06-advanced-functions/06-function-object/5-sum-many-brackets/solution.md +++ b/1-js/06-advanced-functions/06-function-object/5-sum-many-brackets/solution.md @@ -52,8 +52,4 @@ function f(b) { } ``` -<<<<<<< HEAD 이렇게 자기 자신을 호출하지 않고 반환만 하면 다음 호출에서 함수 `f`를 사용할 수 있고, 자기 자신을 또다시 반환해 원하는 만큼 이 과정을 반복할 수 있습니다. `toString` 은 `currentSum` 을 반환해주므로 반환된 함수(객체)를 숫자 혹은 문자열로도 사용할 수 있죠. `Symbol.toPrimitive`나 `valueOf`를 사용해 객체를 숫자나 문자열로 변환할 수도 있습니다. -======= -This `f` will be used in the next call, again return itself, as many times as needed. Then, when used as a number or a string -- the `toString` returns the `currentSum`. We could also use `Symbol.toPrimitive` or `valueOf` here for the conversion. ->>>>>>> upstream/master diff --git a/1-js/06-advanced-functions/06-function-object/article.md b/1-js/06-advanced-functions/06-function-object/article.md index 17b5c71922..d2a7895892 100644 --- a/1-js/06-advanced-functions/06-function-object/article.md +++ b/1-js/06-advanced-functions/06-function-object/article.md @@ -326,11 +326,7 @@ welcome(); // Hello, Guest (중첩 호출이 제대로 동작함) `"func"`이라는 이름은 함수 지역 수준(function-local)에 존재하므로 외부 렉시컬 환경에서 찾지 않아도 됩니다. 외부 렉시컬 환경에선 보이지도 않죠. 함수 표현식에 붙인 이름은 현재 함수만 참조하도록 명세서에 정의되어있기 때문입니다. -<<<<<<< HEAD 이렇게 기명 함수 표현식을 이용하면 `sayHi`나 `welcome` 같은 외부 변수의 변경과 관계없이 `func`이라는 '내부 함수 이름'을 사용해 언제든 함수 표현식 내부에서 자기 자신을 호출할 수 있습니다. -======= -The outer code still has its variable `sayHi` or `welcome`. And `func` is an "internal function name", the way for the function to call itself reliably. ->>>>>>> upstream/master ```smart header="함수 선언문엔 내부 이름을 지정할 수 없습니다." 지금까지 살펴본 '내부 이름'은 함수 표현식에만 사용할 수 있고, 함수 선언문엔 사용할 수 없습니다. 함수 선언문엔 '내부' 이름을 지정할 수 있는 문법이 없습니다. @@ -351,11 +347,7 @@ The outer code still has its variable `sayHi` or `welcome`. And `func` is an "in 함수엔 다양한 프로퍼티를 추가할 수 있습니다. 널리 쓰이는 자바스크립트 라이브러리 상당수에서 이런 커스텀 프로퍼티를 잘 활용하고 있습니다. -<<<<<<< HEAD 이런 라이브러리들은 '주요' 함수 하나를 만들고 여기에 다양한 '헬퍼' 함수를 붙이는 식으로 구성됩니다. [jQuery](https://jquery.com)는 이름이 `$`인 주요 함수로 이루어져 있습니다. [lodash](https://lodash.com)는 주요 함수 `_`에 `_.clone`, `_.keyBy`등의 프로퍼티를 추가하는 식으로 구성되죠. 자세한 정보는 lodash [공식 문서](https://lodash.com/docs)에서 찾아볼 수 있습니다. 이렇게 함수 하나에 다양한 헬퍼 함수를 붙여 라이브러리를 만들면 라이브러리 하나가 전역 변수 하나만 사용하므로 전역 공간을 더럽히지 않는다는 장점이 있습니다. 이름 충돌도 방지할 수 있죠. -======= -They create a "main" function and attach many other "helper" functions to it. For instance, the [jQuery](https://jquery.com) library creates a function named `$`. The [lodash](https://lodash.com) library creates a function `_`, and then adds `_.clone`, `_.keyBy` and other properties to it (see the [docs](https://lodash.com/docs) when you want to learn more about them). Actually, they do it to lessen their pollution of the global space, so that a single library gives only one global variable. That reduces the possibility of naming conflicts. ->>>>>>> upstream/master 이렇게 객체로서의 함수 특징을 이용해 커스텀 프로퍼티를 만들면 함수는 자기 자신을 이용해 원하는 일을 수행할 수 있고, 함수 자기 자신에 딸린 프로퍼티의 기능도 사용할 수 있다는 장점이 있습니다. diff --git a/1-js/06-advanced-functions/07-new-function/article.md b/1-js/06-advanced-functions/07-new-function/article.md index adb621d440..5e02efb18b 100644 --- a/1-js/06-advanced-functions/07-new-function/article.md +++ b/1-js/06-advanced-functions/07-new-function/article.md @@ -92,11 +92,7 @@ getFunc()(); // getFunc의 렉시컬 환경에 있는 값 *!*"test"*/!*가 출 그런데 스크립트가 프로덕션 서버에 반영되기 전, *압축기(minifier)* 에 의해 압축될 때 문제가 발생합니다. 압축기는 스크립트에서 주석이나 여분의 공백 등을 없애 코드 크기를 줄여주는 특수한 프로그램인데 압축기가 지역 변수 이름을 짧게 바꾸면서 문제가 발생하죠. -<<<<<<< HEAD 구체적으로 어떤 부분이 문제가 되는지 예시를 통해 알아봅시다. 함수 내부에 `let userName`라는 변수가 있으면 이 지역변수는 압축기에 의해 `let a` 등(짧은 이름)으로 대체되는데, 이때 `userName` 모두가 `a`로 교체됩니다. `userName`은 지역변수이고, 함수 외부에선 함수 내부에 있는 변수에 접근할 수 없기 때문에 이렇게 해도 전혀 문제가 없죠. 압축기는 단순히 변수를 찾아서 바꾸지 않고 코드 구조를 분석해 기존에 작성한 코드의 기능을 망가뜨리지 않으면서 영리하게 제 역할을 수행합니다. -======= -For instance, if a function has `let userName`, minifier replaces it with `let a` (or another letter if this one is occupied), and does it everywhere. That's usually a safe thing to do, because the variable is local, nothing outside the function can access it. And inside the function, minifier replaces every mention of it. Minifiers are smart, they analyze the code structure, so they don't break anything. They're not just a dumb find-and-replace. ->>>>>>> upstream/master 이런 동작 방식 때문에 `new Function` 문법으로 만든 함수 내부에서 외부 변수에 접근하려고 하면 `userName`은 이미 이름이 변경되었기 때문에 찾을 수 없게 됩니다.