프로토타입 체인

hyxoo·2023년 3월 16일
0

코드스테이츠

목록 보기
20/37
post-thumbnail

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

📌 프로토타입 체인

자바스크립트에서는 객체를 생성할 때, 해당 객체의 프로토타입(Prototype)으로 지정된 객체를 상속받는다. 이때, 해당 객체의 프로토타입 객체가 다른 객체의 프로토타입이 될 수 있다. 이렇게 객체 간에 프로토타입을 이용하여 상속 체인을 형성하는 것을 프로토타입 체인이라고 한다.

✔️ 상속 구현하기

// Person 클래스 (부모)
class Person{
  constructor(name){
    this.name = name;
  } 
// Student 클래스 (자식)
class Student extends Person{
  constructor(name) {
    super(name);
  }
}

❓ .__proto__ 란?

모든 객체는 __proto__ 속성을 가지고 있으며, __proto__는 해당 객체의 프로토타입 객체를 가리킨다.

📎 생성된 인스턴스의 __proto__는 생성자 함수인 Person의 prototype을 참조한다.

class Person{ ... }

let hyesoo = new Person("Hyesoo");
console.log(hyesoo.__proto__ === Person.prototype); // true

📎 부모와 자식 prototype 비교

class Person{ ... }
class Student extends Person{ ... }

let hyesoo = new Person("Hyesoo");
let jimmy = new Student("Jimmy");

console.log(jimmy.__proto__ === hyesoo); // true
console.log(hyesoo.__proto__); // Object.prototype

📌 Object.prototype

Object.prototype은 모든 객체의 조상 객체이다.

📎 Example

toString() 메서드는 객체를 문자열로 변환하여 반환하는 메서드이다.
모든 객체는 Object.prototype의 메서드를 상속받으므로, 이 메서드들은 모든 객체에서 호출이 가능하다.

let str = "Hello, world!";
console.log(str.toString()); // "Hello, world!"

console.log(str.__proto__ === String.prototype) // true

// getPrototypeOf()는 인자로 전달된 객체의 프로토타입 객체를 반환한다.
console.log(Object.getPrototypeOf(String.prototype) === Object.prototype); // true
profile
hello world!

0개의 댓글