You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
There's one more way to create a function. It's rarely used, but sometimes there's no alternative.
4
+
제한적으로 사용하지만, 함수를 생성하는데 한 가지 방법이 더 있습니다. 가끔은 이 방법 외에는 대안이 없을 때도 있죠.
5
5
6
-
## Syntax
6
+
## 문법
7
7
8
-
The syntax for creating a function:
8
+
함수를 만드는 문법은 아래와 같습니다:
9
9
10
10
```js
11
11
let func =newFunction ([arg1[, arg2[, ...argN]],] functionBody)
12
12
```
13
13
14
-
In other words, function parameters (or, more precisely, names for them) go first, and the body is last. All arguments are strings.
14
+
함수의 매개 변수(또는 정확히는 함수들의 이름)가 먼저 오고, 본문이 마지막에 따라옵니다. 모든 인수는 문자열입니다.
15
15
16
-
It's easier to understand by looking at an example. Here's a function with two arguments:
16
+
함수와 두 개의 인수가 있는 아래의 예제를 통해 좀 더 쉽게 이해해 보겠습니다.
17
17
18
18
```js run
19
19
let sum =newFunction('a', 'b', 'return a + b');
20
20
21
21
alert( sum(1, 2) ); // 3
22
22
```
23
23
24
-
If there are no arguments, then there's only a single argument, the function body:
24
+
만약에 인수들이 없다면 오직 하나의 함수 본문을 가진 인수만이 있습니다:
25
25
26
26
```js run
27
27
let sayHi =newFunction('alert("Hello")');
28
28
29
29
sayHi(); // Hello
30
30
```
31
31
32
-
The major difference from other ways we've seen is that the function is created literally from a string, that is passed at run time.
32
+
함수가 문자 그대로 실행될 때 넘겨진다는 것이 가장 다른 점입니다.
33
33
34
-
All previous declarations required us, programmers, to write the function code in the script.
34
+
이전의 모든 함수의 코드 선언문은 스크립트 안에서 쓰였습니다.
35
35
36
-
But`new Function` allows to turn any string into a function. For example, we can receive a new function from a server and then execute it:
36
+
그러나`new Function`이라는 문법은 어떠한 문자열을 함수로 바꾸어주는 역활을 합니다. 예를 들면, 새로운 함수를 서버에서 받아서 실행해야 할 때처럼 말이죠.
37
37
38
38
```js
39
39
let str =... receive the code from a server dynamically ...
@@ -42,13 +42,13 @@ let func = new Function(str);
42
42
func();
43
43
```
44
44
45
-
It is used in very specific cases, like when we receive code from a server, or to dynamically compile a function from a template. The need for that usually arises at advanced stages of development.
45
+
위와 같은 예제는 굉장히 특정한 상황에만 사용됩니다. 서버로부터 코드를 받아올 때 아니면 템플릿으로 부터 함수를 유동적으로 컴파일할 때입니다. 이런 것들이 필요할 때는 좀 더 고급스러운 개발단계가 필요할 때입니다.
46
46
47
-
## Closure
47
+
## 클로져(Closure)
48
48
49
-
Usually, a function remembers where it was born in the special property `[[Environment]]`. It references the Lexical Environment from where it's created.
49
+
함수가 보통 어디에서 작성되었는지에 관한 특수한 프로퍼티는 `[[Environment]]`에 기억되고 생성된 렉시컬 환경을 참고합니다.
50
50
51
-
But when a function is created using `new Function`, its `[[Environment]]` references not the current Lexical Environment, but instead the global one.
51
+
그러나 `new Function`문을 사용해서 함수가 생성되면 `[[Environment]]`은 현재의 렉시컬 환경이 아니고 전역(global)이 됩니다.
52
52
53
53
```js run
54
54
@@ -62,10 +62,10 @@ function getFunc() {
62
62
return func;
63
63
}
64
64
65
-
getFunc()(); //error: value is not defined
65
+
getFunc()(); //에러값이 정의되지 않음
66
66
```
67
67
68
-
Compare it with the regular behavior:
68
+
아래 예제는 일반적인 표현입니다. 비교해보세요:
69
69
70
70
```js run
71
71
functiongetFunc() {
@@ -81,27 +81,27 @@ function getFunc() {
81
81
getFunc()(); // *!*"test"*/!*, from the Lexical Environment of getFunc
82
82
```
83
83
84
-
This special feature of `new Function` looks strange, but appears very useful in practice.
84
+
특수한 기능인 `new Function`이 이상해 보일 수 있습니다만 아주 유용할 때가 있습니다.
85
85
86
-
Imagine that we must create a function from a string. The code of that function is not known at the time of writing the script (that's why we don't use regular functions), but will be known in the process of execution. We may receive it from the server or from another source.
86
+
문자열로부터 함수를 만들어야 하는 상황이 있어야 한다고 생각해보면. 그 함수의 코드는 스크립트를 작성할 때는 알 수 없습니다. (그래서 보통 함수를 사용하지 않죠) 그러나, 서버 또는 다른 출처로부터 받게 되는 것을 실행되는 프로세스는 알 수 있습니다.
87
87
88
-
Our new function needs to interact with the main script.
88
+
새로운 함수는 메인 스크립트와 상호작용해야 할 것입니다.
89
89
90
-
Perhaps we want it to be able to access outer local variables?
90
+
그런데 혹시 그렇게 생성된 함수가 외부의 지역변수에 접근해야 한다면 어떨까요?
91
91
92
-
The problem is that before JavaScript is published to production, it's compressed using a *minifier* -- a special program that shrinks code by removing extra comments, spaces and -- what's important, renames local variables into shorter ones.
92
+
문제는 자바스크립트가 운영에 반영되기 직전에 있습니다. 자바스크립트는 *minifier*라는 특수한 프로그램에 의해 압축됩니다 -- 코드의 특수한 주석이나 빈칸 -- 더 중요한 건 minifier가 지역변수를 짧은 이름으로 바꾸는 것 입니다.
93
93
94
-
For instance, if a function has `let userName`, minifier replaces it`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.
94
+
예를 들어, 만약에 함수가 `let userName` 를 가지고 있다면 minifier 는 그것을`let a`로 (`let a`을 어딘가 사용하고 있다면 다른 문자로) 대체합니다. 그리고 이런 작업은 모든 코드에서 진행됩니다. 보통 이런 작업은 값들이 지역변수라 안전하지만, 이름이 바뀌어서 외부 함수에서는 접근할 수 없게 됩니다. 그리고 함수의 내부에서 minifier는 선언된 모든 곳을 수정합니다. Minifiers 는 똑똑하고 코드의 구조를 분석하기 때문에 무조건 찾아서 바꾸지는 않기 때문에 어떠한 곳도 망가뜨리진 않지만,
95
95
96
-
But, if `new Function`could access outer variables, then it would be unable to find `userName`, since this is passed in as a string *after* the code is minified.
96
+
만약 `new Function`구문이 외부 변수들에 접근하려 한다면 *이후의* 코드는 minified 되었기 때문에 `userName` 이라는 것은 찾을 수 없을 것입니다.
97
97
98
-
**Even if we could access outer lexical environment in `new Function`, we would have problems with minifiers.**
98
+
**`new Function` 문법이 외부 렉시컬 환경에 접근할 수 있더라도 minifiers에 의한 문제는 여전히 발생할 수 있습니다.**
99
99
100
-
The "special feature" of`new Function` saves us from mistakes.
100
+
이런 실수로부터 예방하기 위해`new Function`에는 특별한 기능이 있습니다.
101
101
102
-
And it enforces better code. If we need to pass something to a function created by `new Function`, we should pass it explicitly as an argument.
102
+
그리고 좀더 좋은 코드를 제공합니다. `new Function`이란 문법을 사용한 함수에 무언가를 넘기려고 할대는 명시적으로 인수(argument)로 넘기는것이 좋습니다.
103
103
104
-
Our "sum" function actually does that right:
104
+
아래의 "sum"함수는 명시적으로 전달하는것을 잘 표현하고 있습니다.
105
105
106
106
```js run
107
107
*!*
@@ -111,27 +111,27 @@ let sum = new Function('a', 'b', 'return a + b');
111
111
let a =1, b =2;
112
112
113
113
*!*
114
-
//outer values are passed as arguments
114
+
//필요한 값들이 매개변수로 전달되었음
115
115
alert( sum(a, b) ); // 3
116
116
*/!*
117
117
```
118
118
119
-
## Summary
119
+
## 요약
120
120
121
-
The syntax:
121
+
문법:
122
122
123
123
```js
124
124
let func =newFunction(arg1, arg2, ..., body);
125
125
```
126
126
127
-
For historical reasons, arguments can also be given as a comma-separated list.
127
+
오래전부터 인수들은 콤마로 구별된 리스트로 사용할 수 있습니다.
128
128
129
-
These three mean the same:
129
+
아래의 세 가지 표현은 다르지만 같은 표현입니다.
130
130
131
131
```js
132
-
newFunction('a', 'b', 'return a + b'); //basic syntax
133
-
newFunction('a,b', 'return a + b'); //comma-separated
134
-
newFunction('a , b', 'return a + b'); //comma-separated with spaces
132
+
newFunction('a', 'b', 'return a + b'); //기본 문법
133
+
newFunction('a,b', 'return a + b'); //콤마로 구별된
134
+
newFunction('a , b', 'return a + b'); //콤마와 스페이스로 구별된
135
135
```
136
136
137
-
Functions created with `new Function`, have `[[Environment]]` referencing the global Lexical Environment, not the outer one. Hence, they cannot use outer variables. But that's actually good, because it saves us from errors. Passing parameters explicitly is a much better method architecturally and causes no problems with minifiers.
137
+
`new Function`으로 생성된 함수는 전역 렉시컬환경을 참조하는 `[[Environment]]`를 가지고 있습니다. 그래서 그 함수는 외부 변수를 사용할 수 없습니다. 이런 현상은 에러를 방지하므로 실제로는 좋은 현상입니다. 외부 변수에 접근할 때, 명시적으로 매개변수로 넘기는 것이 minifiers와 문제가 생기지 않게 하는 설계적으로 더 좋은 방법이기 때문입니다.
0 commit comments