The prototype is itself an object, so the prototype will have its own prototype, making what's called a prototype chain
출처: mdn Object prototypes
.prototype
: 그 자신의 부모 역할을 담당하는 객체(즉, 프로토타입)을 가리키는 메소드.__proto__
: 부모 클래스의 프로토타입, 혹은 '부모의 부모 클래스'의 프로토타입을 탐색할 때 사용하는 메소드//Person이라는 클래스 생성
class Person{
constructor(firstName, lastName, age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
};
};
//Person의 프로토타입에 breathe라는 함수 생성
Person.prototype.breathe = function () {
console.log('호흡을 합니다.');
};
//새로운 인스턴스 생성
const jim = new Person('Jim', 'smith', 42);
const pam = new Person('Pam', 'smith', 41);
console.log(jim.age); //42
jim.breathe(); //'호흡을 합니다.'
Object
: JavaScript의 거의 모든 객체는 Object
의 인스턴스이므로 일반적인 객체는 Object.prototype
에서 속성(메서드 포함)을 상속 또는 재정의 할 수 있음div
element의 상속관계.call
, .object.create
, .prototype.constructor
사용하기function Animal (name, energy) {
this.name = name;
this.energy = energy;
};
Animal.prototype.eat = function (amount) {
console.log(`${this.name} is eating.`);
this.energy += amount;
};
Animal.prototype.sleep = function (length) {
console.log(`${this.name} is sleeping.`);
this.energy += length;
};
Animal.prototype.play = function (length) {
console.log(`${this.name} is playing.`);
this.energy -= length;
};
//속성 상속하기
function Dog (name, energy, breed) {
Animal.call(this, name, energy);
this.breed = breed;
}
//메소드 상속하기
Dog.prototype = Object.create(Animal.prototype);
//새로운 메소드 추가하기
Dog.prototype.bark = function () {
console.log('Woof Woof');
this.energy -= .1;
};
//생성자 함수 reset하기
Dog.prototype.constructor = Dog;
//새로운 인스턴스 만들기
const charlie = new Dog ('Charlie', 10, 'Goldendoodle');
extends
와 super
사용하기class Animal {
constructor(name, energy) {
this.name = name;
this.energy = energy;
};
eat(amount) {
console.log(`${this.name} is eating.`);
this.energy += amount;
};
sleep(length) {
console.log(`${this.name} is sleeping.`);
this.energy += length;
};
play(length) {
console.log(`${this.name} is playing.`);
this.energy -= length;
};
};
//Dog 클래스를 Animal 클래스의 자식으로 만들기
class Dog extends Animal{
constructor(name, energy, breed) {
//부모 오브젝트의 함수 호출하기
super(name, energy);
this.breed = breed;
}
bark() {
console.log('Woof Woof');
this.energy -= .1;
};
};
const leo = new Dog('Leo', 7, 'Goldendoodle');
Reference
프로토타입 체인 예시
상속 구현하기