Skip to content

Commit

Permalink
ADD: 6-3
Browse files Browse the repository at this point in the history
  • Loading branch information
Leejha committed Jun 22, 2023
1 parent e127031 commit 55c589b
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions ch06/6-3.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# 6-3 proto의 this 바인딩

```js
var 공장 = function (brand) {
this.brand = brand;
};

공장.prototype.getBrand = function () {
return this.brand;
};

var 아이폰 = new 공장("Apple");

//__proto__ 프로퍼티를 통해 prototype의 메서드 호출
아이폰.__proto__.getBrand(); // undefined
```

위 예제에서 getBrand 메서드를 호출할 때, this는 아이폰 인스턴스가 아닌, `아이폰.__proto__`가 된다.

`아이폰.__proto__` 내부에는 brand 프로퍼티가 없기 때문에 undefined를 반환한다.

그런데 proto 는 생략가능한 프로퍼티이다.

따라서 다음과 같이 사용할 수도 있다. instance에 getBrand() 메서드가 없다면, 생성자의 prototype 으로 올라가서 getBrand()를 찾아 실행한다.

```js
아이폰.getBrand(); // Apple
```

이 때 this 는 아이폰을 바라보므로 원했던 값이 반환된다.

0 comments on commit 55c589b

Please sign in to comment.