Web Dev/1. JS 문법 관련

__proto__ dunderscore proto

hYhY1234 2020. 9. 26. 21:52
728x90

 

 

__proto__가 항상 뭔지 헷갈렸는데 드디어 정리한다.

 

 

user라는 객체가 name, score 와 increment라는 score를 증가시키는 함수가 필요할때

increment함수는 user1, user2, user3... 가 모두 똑같이 쓸거고,

name과 score만 각 객체마다 다를거다. 

 

즉,

 

const user1 = {

name: "제시",

score: 99,

increment: function() { this.score++}

}

 

const user2 = {

name: "효리",

score: 80,

increment: function() { this.score++}

}

 

이런식으로 name과 score만 다르지 increment는 똑같은게 반복인데, 저런식으로 각 객체에 incremenet를 다 정의하는 것은 메모리 낭비이다. 그래서 자바스크립트에서 객체를 생성할때

 

const userFunctionStore = {

 increment: function() { this.score++}

}

 

const user = Object.create(userFunctionStore) ;

 

user.name = "제시";

user.score = 88;

 

 

를 사용하면 Object.create()를 했을때처럼 빈 객체를 반환하는 것은 맞지만

userFunctionStore 객체와 연결을 해서 

 

user.increment() 를 했을때 user객체 내에서 바로 increment함수를 찾지못하면 객체와 연결된 객체를 찾아가서 increment를 찾아서 수행한다. 

 

그리고 userFunctionStore 로 가는 링크를 __proto__에 저장하는 것이다. 

 

긍까 user.뭐 이런식으로 쓸려고했더니, user객체에 바로없으면 놀라지 않고, __proto__ 에 있는데로 가서 있니? 확인하는 것이다.