[JavaScript] 객체 지향 프로그래밍 | 프로토타입 체인, DOM과 프로토타입, 상속 구현하기

Eunji Lee·2022년 11월 21일
0

[TIL] JavaScript

목록 보기
18/22
post-thumbnail

Chatpter2. 프로토타입

2-2. 프로토타입 체인

프로토타입 체인

  • 객체 지향 프로그래밍의 특성 중 하나인 상속을 JavaScript에서 구현하기 위해 사용됨
  • 프로토타입 그 자신도 일종의 객체이기 때문에, 그 자신의 부모 역할을 담당하는 객체(즉, 프로토타입)을 가지고 있으며, 이를 프로토타입 체인이라고 부른다.

    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(); //'호흡을 합니다.'




DOM과 프로토타입

  • Object: JavaScript의 거의 모든 객체는 Object의 인스턴스이므로 일반적인 객체는 Object.prototype에서 속성(메서드 포함)을 상속 또는 재정의 할 수 있음
  • div element의 상속관계



상속 구현하기

ES5 문법

  • .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');

ES6 문법

  • extendssuper 사용하기
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
프로토타입 체인 예시
상속 구현하기

0개의 댓글