[JavaScript] Prototype

HYl·2022년 3월 21일
0

TIL

목록 보기
3/3

프로토타입 기반 언어?

JavaScript는 흔히 프로토타입 기반 언어(prototype-based language)라 불린다.
모든 객체들이 메소드와 속성들을 상속 받기 위한 템플릿으로써 프로토타입 객체(prototype object)를 가진다는 의미이다.

프로토타입 객체 이해하기.

const x = {};
const y = {};
console.log(x);
console.log(y);

객체 안에 아무 것도 들어있지 않은 x와 y를 console.log에 각각 출력해보면, Prototype이라는 것이 들어있다.
Prototype 은 Object라고 명시되어 있다.
즉, 자바스크립트에서 모든 object는 Prototype인 Object를 상속한다.

이처럼 프로토타입 안에 오브젝트에서 쓸 수 있는 기본적인 함수들이 많이 있는 것을 확인해 볼 수 있는데 이것들을 다 사용할 수 있다
( x.toString(), x.toLocaleString() 등등 다 사용 할 수 있다. )

x와 y는 동일한 오브젝트의 프로토를 상속하고 있기 때문에,
x의 proto와 y의 proto는 동일한 결과 값을 가진다.

console.log(x.__proto__ === y.__proto__) // true

array

array라는 변수의 오브젝트는, Array를 상속하고, 또 이 Array이라는 프로토는 Object를 상속한다.

그래서 js에 있는 모든 object들은 Object라는 Proto를 가지게 되는 것

또한, 어떤 종류의 오브젝트 상관없이 무조건 toString을 이용할 수 있는 것


Instance member level

function CoffeeMachine(beans) {
  	this.beans = beans;
  	this.makeCoffee = shots => {
      	console.log('making coffee');
    };
}

const machine1 = new CoffeeMachine(10);
const machine2 = new CoffeeMachine(20);
console.log(machine1);
console.log(machine2);

Prototype member level

function CoffeeMachine(beans) {
  	this.beans = beans;
}

// Prototype member level
CoffeeMachine.prototype.makeCoffee = shots => {
  console.log('making coffee');
};
const machine1 = new CoffeeMachine(10);
const machine2 = new CoffeeMachine(20);
console.log(machine1);
console.log(machine2);

오브젝트 안에 있던 makeCoffee를
프로토를 열었을 때, makeCoffee가 공통적으로 들어있게 변경되어졌다.

machine1과 2는 CoffeeMachine을 상속하고
CoffeeMachine은 Object를 상속한다.


Create

LatteMachine의 프로토타입은 Object.create를 써서 CoffeeMachine에 있는 프로토타입과 연결해주었다.

LatteMachine은 CoffeeMachine을 상속하게 되고, 결국엔
LatteMachine도 makeCoffee라는 함수를 이용할 수 있다.


function LatteMachine(milk) {
  this.milk = milk;
}
LatteMachine.prototype = Object.create(CoffeeMachine.prototype);

const latteMachine = new LatteMachine(123);
console.log(latteMachine);
latteMachine.makeCoffee();

마무리

자바스크립트에서는 타입스크립트처럼 인터페이스나, 제네릭같은 다양한 것들은 없지만 프로토타입을 이용해서 상속을 구현할 수 있다.

프로토타입은 자바스크립트에서 객체지향 프로그래밍 상속을 하기 위하여 쓰는 것이고, 코드를 재사용하기 위해서 사용한다.

profile
꾸준히 새로운 것을 알아가는 것을 좋아합니다.

0개의 댓글