프로토타입

hyxoo·2023년 3월 15일
0

코드스테이츠

목록 보기
19/37
post-thumbnail

📝 [Section2_Unit2] 객체 지향 프로그래밍 #3

📌 Prototype

JavaScript는 흔히 프로토타입 기반 언어(prototype-based language)라 불립니다.— 모든 객체들이 메소드와 속성들을 상속 받기 위한 템플릿으로써 프로토타입 객체(prototype object)를 가진다는 의미입니다. 프로토타입 객체도 또 다시 상위 프로토타입 객체로부터 메소드와 속성을 상속 받을 수도 있고 그 상위 프로토타입 객체도 마찬가지입니다.

정확히 말하자면 상속되는 속성과 메소드들은 각 객체가 아니라 객체의 생성자의 prototype이라는 속성에 정의되어 있습니다.

✔️ Prototype 접근하기

class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  eat() {
    console.log(`${this.name}가 밥을 먹었다.`);
  }
}

let hyesoo = new Person('혜수', 26);

console.log(Person.prototype.constructor === Person); // true
console.log(Person.prototype === hyesoo.__proto__); // true
console.log(Person.prototype.eat === hyesoo.eat); // true

❗️ class ↔️ prototype ↔️ instance

  • prototype은 클래스를 만들면 자동으로 생성된다.
  • .prototype으로 Person클래스의 prototype에 접근할 수 있다.
  • __proto__hyesoo객체를 생성할 때 같이 생성된 속성으로 Person 객체의 prototype을 가르킨다.
profile
hello world!

0개의 댓글