본문 바로가기

javaScripts

__proto__, constructor, prototype 의 관계

자바스크립트에서 함수는 객체이다.

그래서 

function Person() {} 와 var Person = new Function() {} 은 같은것이다.

 

prototype에 대해 예를 들어 설명해보면,

-----------------------------------------------------------------------

function Person(name, first, second) {

   this.name = name;

   this.first = first;

   this.second = second;

}

 

Person.prototype.sum = function() {}

 

var kim = new Person("kim", 1, 2)

------------------------------------------------------------------------

위의 코드를 실행시킨 결과는 아래 그림과 같다.

 

 

코드를 실행시키면 Person이라고 하는 객체, Person의 prototype이라는 객체, 그리고 kim 이라는 객체가 생성된다.

이때 Person의 prototype이라는 속성은 Person's prototype을 가리키고, 

Person's prototype의 constructor라는 속성은 Person이라는 객체를 가리키며,

kim의 __proto__라는 속성은 Person's prototype을 가리키게 된다.

 

만약 kim.sum()을 실행시키면 먼저 kim이라는 객체에 sum이라는 속성이 있는지를 탐색하고,

없으면 __proto__를 통해 Person's prototype에 sum이라는 속성이 있는지를 탐색하게 된다.

 

추가적으로, Object.create()에  대해서는 예를들어

var obj1 = Object.create(obj2) 

와 같은 코드를 실행시킨다면, 이 의미는

obj1의 __proto__속성이 가리키는 객체가 obj2가 된다는 것이다.

그래서 obj1에서 obj2의 속성이나 메소드에 접근할 수 있게된다.

'javaScripts' 카테고리의 다른 글

Inheritance Patterns  (0) 2020.01.11
About Object  (0) 2019.12.27
12/26  (0) 2019.12.26
12/25  (0) 2019.12.25