📝 [Section2_Unit2] 객체 지향 프로그래밍 #3
JavaScript는 흔히 프로토타입 기반 언어(prototype-based language)라 불립니다.— 모든 객체들이 메소드와 속성들을 상속 받기 위한 템플릿으로써 프로토타입 객체(prototype object)를 가진다는 의미입니다. 프로토타입 객체도 또 다시 상위 프로토타입 객체로부터 메소드와 속성을 상속 받을 수도 있고 그 상위 프로토타입 객체도 마찬가지입니다.
정확히 말하자면 상속되는 속성과 메소드들은 각 객체가 아니라 객체의 생성자의 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
prototype
은 클래스를 만들면 자동으로 생성된다..prototype
으로 Person
클래스의 prototype
에 접근할 수 있다.__proto__
는 hyesoo
객체를 생성할 때 같이 생성된 속성으로 Person
객체의 prototype
을 가르킨다.