-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
30 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 는 아이폰을 바라보므로 원했던 값이 반환된다. |