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
As we can see, the output shows not "John" as `this.firstName`, but `undefined`!
31
+
보이듯이, 결과값는 "John"이 `this.firstName` 이 아니라 `undefined` 입니다!
32
32
33
-
That's because`setTimeout`got the function `user.sayHi`, separately from the object. The last line can be rewritten as:
33
+
그 이유는`setTimeout`이 `user.sayHi`함수를 객체로 부터 독립적으로 가져왔기 때문입니다. 마지막 라인은 이렇게 다시 쓰여질 수 있습니다.
34
34
35
35
```js
36
36
let f =user.sayHi;
37
-
setTimeout(f, 1000); //lost user context
37
+
setTimeout(f, 1000); // user 컨텍스트를 잃어버렸음
38
38
```
39
39
40
-
The method `setTimeout` in-browser is a little special: it sets `this=window`for the function call (for Node.js, `this`becomes the timer object, but doesn't really matter here). So for `this.firstName`it tries to get `window.firstName`, which does not exist. In other similar cases as we'll see, usually `this` just becomes `undefined`.
40
+
`setTimeout`매서드는 브라우저 안에서는 조금 특별합니다. 그것은 `this=window`을 함수를 호출하기 위해서 셋팅합니다 (Node.js 에서는 `this`가 타이머 객체가 됩니다. 여기서는 크게 상관은 없습니다). 그래서 `this.firstName`은 존재하지 않는 `window.firstName`을 가져오려고 합니다. 다른 상황에서도 종종 `this`가 `undefined`로 되는것을 볼 것입니다.
41
41
42
-
The task is quite typical -- we want to pass an object method somewhere else (here -- to the scheduler) where it will be called. How to make sure that it will be called in the right context?
42
+
이것은 매우 전형적 작업입니다. 호출 될 곳에서 객체 메서드를 다른 곳으로 (여기서는 스케쥴러에) 전달하려고합니다. 어떻게 올바른 컨텍스트에서 호출되는 것을 확인할수 있을까요?
43
43
44
-
## Solution 1: a wrapper
44
+
## 첫번째 해결책: a wrapper
45
45
46
-
The simplest solution is to use a wrapping function:
46
+
가장 간단한 해결방법은 wrapping 함수를 사용하는 것입니다.
47
47
48
48
```js run
49
49
let user = {
@@ -60,17 +60,17 @@ setTimeout(function() {
60
60
*/!*
61
61
```
62
62
63
-
Now it works, because it receives `user` from the outer lexical environment, and then calls the method normally.
63
+
이제 작동합니다, 왜냐하면 `user`를 외부 렉시컬 환경으로 받아서 메서드를 보통때 처럼 호출했기 때문입니다.
Looks fine, but a slight vulnerability appears in our code structure.
71
+
위의 코드는 괜찮아 보입니다만, 코드 구조에는 약간 취약한 점이 있습니다.
72
72
73
-
What if before `setTimeout` triggers (there's one second delay!) `user` changes value? Then, suddenly, it will call the wrong object!
73
+
`setTimeout`이 시작되기 전에 (1 초의 지연이 있습니다!) `user`가 값을 변경하면 어떻게 될까요? 그렇다면 갑자기 잘못된 개체를 호출할것 입니다!
74
74
75
75
76
76
```js run
@@ -83,30 +83,30 @@ let user = {
83
83
84
84
setTimeout(() =>user.sayHi(), 1000);
85
85
86
-
// ...within 1 second
86
+
// ...1초 안에
87
87
user = { sayHi() { alert("Another user in setTimeout!"); } };
88
88
89
-
//Another user in setTimeout?!?
89
+
//setTimeout에 또 다른 user 가?!?
90
90
```
91
91
92
-
The next solution guarantees that such thing won't happen.
92
+
다음 해결책은 이러한 현상이 일어나는걸 방지합니다.
93
93
94
-
## Solution 2: bind
94
+
## 두번째 해결방법: bind
95
95
96
-
Functions provide a built-in method [bind](mdn:js/Function/bind)that allows to fix `this`.
96
+
함수들은 `this`를 수정하도록 하는 내장 매서드인 [bind](mdn:js/Function/bind)를 제공합니다.
97
97
98
-
The basic syntax is:
98
+
기본 문법
99
99
100
100
```js
101
-
//more complex syntax will be little later
101
+
//더 복잡한 문법은 나중에 다루겠습니다
102
102
let boundFunc =func.bind(context);
103
103
````
104
104
105
-
The result of`func.bind(context)` is a special function-like "exotic object", that is callable as function and transparently passes the call to `func` setting `this=context`.
105
+
`func.bind(context)`의 결과는 "exotic object"같은 특별한 함수입니다, 이것은 함수로서 호출 가능하고`func`에`this = context`를 투명하게 전달합니다.
106
106
107
-
In other words, calling `boundFunc` is like `func` with fixed `this`.
107
+
즉,`boundFunc`를 호출하는 것은 `this`가 고정 된 `func`와 같습니다.
108
108
109
-
For instance, here `funcUser` passes a call to `func` with `this=user`:
109
+
예를 들면 여기서`funcUser`는 `this = user` 를 가지고 `func`를 호출합니다.
110
110
111
111
```js run
112
112
let user = {
@@ -123,9 +123,9 @@ funcUser(); // John
123
123
*/!*
124
124
```
125
125
126
-
Here`func.bind(user)` as a "bound variant" of `func`, with fixed `this=user`.
126
+
여기`func.bind(user)`는 `func`의 "바운드 변수"로 고정 된 `this = user`를 가지고 있습니다.
127
127
128
-
All arguments are passed to the original `func` "as is", for instance:
128
+
모든 인수는 원래 `func`"있는 그대로"으로 전달됩니다. 예를 들면
129
129
130
130
```js run
131
131
let user = {
@@ -140,11 +140,11 @@ function func(phrase) {
140
140
let funcUser = func.bind(user);
141
141
142
142
*!*
143
-
funcUser("Hello"); // Hello, John (argument "Hello" is passed, and this=user)
143
+
funcUser("Hello"); // Hello, John ("Hello" 인수가 넘겨졌고 this=user 입니다)
144
144
*/!*
145
145
```
146
146
147
-
Now let's try with an object method:
147
+
이제 객체 메서드를 사용해 보겠습니다.
148
148
149
149
150
150
```js run
@@ -164,9 +164,9 @@ sayHi(); // Hello, John!
164
164
setTimeout(sayHi, 1000); // Hello, John!
165
165
```
166
166
167
-
In the line `(*)` we take the method `user.sayHi`and bind it to `user`. The `sayHi` is a "bound" function, that can be called alone or passed to `setTimeout` -- doesn't matter, the context will be right.
167
+
`(*)`줄에서 `user.sayHi`메소드를 가져 와서 `user`에 바인드합니다. `sayHi`는 단독으로 호출되거나 `setTimeout`에 전달 될 수있는 "바운드 (bound)"함수입니다 - 컨텍스트는 맞기때문에 중요하지는 않습니다.
168
168
169
-
Here we can see that arguments are passed "as is", only `this` is fixed by `bind`:
169
+
인수는 "있는 그대로"전달되고, 단지 "this"만이 `bind`에 의해 고정된다는 것을 알 수 있습니다.
170
170
171
171
```js run
172
172
let user = {
@@ -178,12 +178,12 @@ let user = {
178
178
179
179
let say = user.say.bind(user);
180
180
181
-
say("Hello"); // Hello, John ("Hello" argument is passed to say)
182
-
say("Bye"); // Bye, John ("Bye" is passed to say)
181
+
say("Hello"); // Hello, John ("Hello"인수가 say로 넘겨졌음)
182
+
say("Bye"); // Bye, John ("Bye"가 say 로 넘겨졌음)
183
183
```
184
184
185
185
````smart header="Convenience method: `bindAll`"
186
-
If an object has many methods and we plan to actively pass it around, then we could bind them all in a loop:
186
+
객체가 많은 메서드를 가지고 있고 그것을 능동적으로 전달할 계획이라면, 모든 것을 루프로 묶을 수 있습니다.
187
187
188
188
```js
189
189
for (let key in user) {
@@ -193,11 +193,11 @@ for (let key in user) {
193
193
}
194
194
```
195
195
196
-
JavaScript libraries also provide functions for convenient mass binding , e.g. [_.bindAll(obj)](http://lodash.com/docs#bindAll) in lodash.
196
+
자바스크립트 라이브러리들은 편리한 매스 바인딩(mass binding)함수들을 제공하고 있습니다. 예를들면, lodash 에는 [_.bindAll(obj)](http://lodash.com/docs#bindAll)가 있습니다.
197
197
````
198
198
199
-
## Summary
199
+
## 요약
200
200
201
-
Method `func.bind(context, ...args)` returns a "bound variant" of function `func` that fixes the context `this` and first arguments if given.
201
+
메서드`func.bind(context, ...args)`는 문맥 `this`와 첫 번째 인수가 주어지면 수정하는 `func` 함수의 "바운드 변수"를 반환합니다.
202
202
203
-
Usually we apply `bind` to fix `this` in an object method, so that we can pass it somewhere. For example, to `setTimeout`. There are more reasons to `bind` in the modern development, we'll meet them later.
203
+
보통 객체 메소드에서 `this` 를 고치기 위해 `bind`를 적용하여 어딘가에 전달할 수 있습니다. 예를 들면, `setTimeout`같은 메서드입니다. 현대적인 개발에 'bind'하는 이유는 더 있습니다. 나중에 다시 다루어 보겠습니다.
0 commit comments