본문 바로가기

자바스크립트

Javascript’s __proto__ vs prototype

1. __proto__란?

person 이라는 객체는 아래와 같이 name, age 그리고 gender 속성을 가지고 있습니다.

let person = {
  name: "Nil",
  age: 18,
  gender: "male"
}

console.dir을 이용해서 person 객체를 호출하면 __protp__ 속성을 확인 할 수 있습니다.

__proto__ 속성은 디폴트 속성으로 객체마다 다 생성됩니다.

이 __proto__속성은 prototype 객체를 향해 가르키고 있습니다.

그러므로 person객체의__proto__ 속성은 Object.prototype 방향으로 가르키고있습니다.

person.__proto__ === Object.prototype
>> true

teacher이라는 객체를 생성합니다. 앞서 생성한 person 객체의 속성과 동일하게 생성하되 subject 속성을

추가합니다.

let teacher = {name: "nil", age: 18, gender: "male", subject: "JS"}

teacher 객체와 person 객체는 공통되는 속성이 존재 합니다. person 객체로부터 속성을 상속받아서 사용하면 

더 좋을 것 같습니다.

그럴려면 앞서 생성한 teacher 객체를 버리고 다시 만듭니다.

let teacher = { subject: "javascript" }

아래와 같은 구조를 가지게 됩니다.

https://levelup.gitconnected.com/javascripts-proto-vs-prototype-a21ec7f25bc1에서 참고한 이미지

Object.setPrototypeOf() 함수를 이용하여 teacher 객체가 person 객체로 부터 상속 받을 수 있게 합니다.

Object.setPrototypeOf(teacher, person)

 

teacher 객체의 __proto 속성은 person 객체를 가르키고 있다는 결과를 확인 할 수 있습니다.

teacher.__proto__ === person
>> true

teacher.name 리턴값은  teacher.__proto__ 로 부터

teacher.age 리턴값은 teacher.__proto__로 부터

teacher.subject 리턴값은 teacher 객체로 부터

teacher.toString 리턴값은 teache.__proto__.__proto__ 로 부터 가져온다는 것을 확인 할 수 있다.

더불어 만약 person 객체에서 속성값을 변경한다면 위임받고 있는 teacher 객체의 속성값도 같이 변경된다.

 

결론: 객체마다 존재하는 __proto__ 속성은 prototype 객체를 가르킨다.

 

참고: https://levelup.gitconnected.com/javascripts-proto-vs-prototype-a21ec7f25bc1

'자바스크립트' 카테고리의 다른 글

modal popup 구현  (0) 2021.09.06
script 태그의 async와 defer 속성  (0) 2021.08.26
생성자 함수의 객체 생성  (0) 2021.06.09
함수 객체의 프로퍼티  (0) 2021.06.08
Unexpected comma using map()  (0) 2021.05.22