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
We can use such approach if we are sure that`"constructor"`property has the correct value.
1
+
`"constructor"`프로퍼티에 제대로 된 값이 저장되어있다면 위와 같은 접근법이 가능합니다.
2
2
3
-
For instance, if we don't touch the default`"prototype"`, then this code works for sure:
3
+
기본`"prototype"`를 변경하지 않았다면 아래 예시는 의도한 대로 동작합니다.
4
4
5
5
```js run
6
6
functionUser(name) {
@@ -10,14 +10,14 @@ function User(name) {
10
10
let user=newUser('John');
11
11
let user2=newuser.constructor('Pete');
12
12
13
-
alert(user2.name );// Pete (worked!)
13
+
alert(user2.name );// Pete (잘 동작하네요!)
14
14
```
15
15
16
-
It worked, because`User.prototype.constructor == User`.
16
+
`User.prototype.constructor == User`이기 때문에 위 예시는 제대로 동작합니다.
17
17
18
-
..But if someone, so to speak, overwrites`User.prototype` and forgets to recreate`constructor` to reference`User`, then it would fail.
18
+
그런데 누군가가`User.prototype`를 덮어쓰고`User`를 참조하는`constructor`를 다시 만들어주는 걸 잊었다면 문제의 접근법은 실패합니다.
19
19
20
-
For instance:
20
+
예시:
21
21
22
22
```js run
23
23
functionUser(name) {
@@ -33,12 +33,12 @@ let user2 = new user.constructor('Pete');
33
33
alert(user2.name );// undefined
34
34
```
35
35
36
-
Why`user2.name` is`undefined`?
36
+
왜`user2.name`이`undefined`가 될까요?
37
37
38
-
Here's how`new user.constructor('Pete')` works:
38
+
그 이유는`new user.constructor('Pete')`가 아래와 같이 동작하기 때문입니다.
39
39
40
-
1.First, it looks for`constructor` in`user`. Nothing.
41
-
2.Then it follows the prototype chain. The prototype of`user` is`User.prototype`, and it also has nothing.
42
-
3.The value of`User.prototype` is a plain object`{}`, its prototype is`Object.prototype`. And there is`Object.prototype.constructor == Object`. So it is used.
40
+
1.`new user.constructor('Pete')`는`user`에서`constructor`를 찾는데 아무것도 찾지 못합니다.
41
+
2.객체에서 원하는 프로퍼티를 찾지 못했기 때문에 프로토타입에서 검색을 시작합니다.`user`의 프로토타입은`User.prototype`인데,`User.prototype`은 빈 객체입니다.
42
+
3.`User.prototype`은 일반 객체`{}`이고, 일반 객체의 프로토타입은`Object.prototype`입니다.`Object.prototype.constructor == Object`이므로`Object`가 사용됩니다.
43
43
44
-
At the end, we have`let user2 = new Object('Pete')`. The built-in`Object` constructor ignores arguments, it always creates an empty object, similar to`let user2 = {}`, that's what we have in`user2` after all.
44
+
결국에`let user2 = new user.constructor('Pete');`는`let user2 = new Object('Pete')`가 됩니다. 그런데`Object`의 생성자는 인수를 무시하고 항상 빈 객체를 생성합니다. 따라서`let user2 = new Object('Pete')`는`let user2 = {}`와 같다고 생각할 수 있습니다.`user2.name`이`undefined`인 이유가 여기에 있습니다.