[JavaScript] ProtoType

·2022년 2월 3일

JavaScript

목록 보기
6/9
post-thumbnail

[[Prototype]]은 숨김 프로퍼티 이자 내부 프로퍼티 이다.

__proto__

아니 마크다운 적용돼서 ㅅㅂ
암튼 저거를 property에 넣거나 method로 사용해서 prototype으로 만들 객체를 정해주면 된다


method로 이용한 방식
  let animal = {
    eats: true
  };
  let rabbit = {
    jumps: true
  };
  rabbit.__proto__ = animal;

Property에 넣어서 적용한 방식

  let animal = {
    eats: true
  };
  let rabbit = {
    jumps: true
    __proto__: animal
  };

아 개그튼 색상 코드블락 이게 더 잘보이네

객체에서 없는 Property가 있다면, Prototype에서도 한번 검사를 해준다.

rabbit의 경우, eats라는 property가 없지만 prototype으로 지정된 animal에 eats가 있기 때문에 요걸 이용함!


prototype의 특징

  1. 읽기 전용이다.
  2. 객체나 null을 가르킨다.
  3. 한번에 하나만 가질 수 있다.

예시 문제

  1. sepeedy.eat("apple")
  • 객체 speedy는 eat이라는 property가 없음
    - prototype인 객체 hamster를 찾아본다.
    • eat이라는 function property가 있다.
    • this.stomach.push(food) 진행
    • 여기선 speedy가 호출한 객체이므로, this는 speedy가 된다.
      speedy.stomach.push(food);
    • speedy는 stomach를 갖고있지 않고, prototype인 hamster를 찾아보니 stomach를 갖고있음. 여기에 추가하게된다
    • push의 성질에 따라 객체 내부의 hamster - stomach 배열에 추가.
      stomach: ["apple"]
    • 이렇게 되면 speedy의 stomach에만 apple이 들어간게 아니라, speedy와 lazy의 prototype인 hamster에 공유가 된거라 둘 다 stomach에 apple을 갖게됨.
  1. this.stomach = [food]로 변경
  • 이렇게 되면
let hamster = {
  stomach: [],

  eat(food) {
    //this.stomach.push(food);
    this.stomach = [food];
  }
};

let speedy = {
  __proto__: hamster
};

let lazy = {
  __proto__: hamster
};

speedy.eat("apple");
alert(speedy.stomach);

alert(lazy.stomach);

이런식으로 고쳐주면 아예 호출한 . 앞의 객체에 새로운 property를 만들어주는거다!!
그럼 각자의 stomach가 생기게 되고, 음식도 각각 들어가게 되니까 문제 해결 왈료!!!

profile
어?머지?

0개의 댓글