본문 바로가기

JavaScript

JavaScript: 프로토타입과 클래스

반응형

자바스크립트에서 프로토타입의 역할은 function 키워드로 객체 생성자를 만들고, 그 객체 생성자를 new 키워드를 통해 만든 다른 객체들끼리 공유할 수 있는 어떠한 값이나 함수를 prototype에 넣어주는 것이다.

 

클래스(Class)가 없는 자바스크립트에서 프로토타입(Prototype)의 개념은 아주 중요하다. 여기서는 아주 간단하게만 알아보고 나중에 더 자세하게 알아보자.

 

function Animal(type, name, sound) {
  this.type = type;
  this.name = name;
  this.sound = sound;
}

Animal.prototype.say = function () {
  console.log(this.sound);
};

Animal.prototype.sharedValue = 1;

const dog = new Animal("개", "멍멍이", "멍멍");
const cat = new Animal("고양이", "야옹이", "야옹");

dog.say(); // 멍멍
cat.say(); // 야옹

console.log(dog.sharedValue); // 1
console.log(cat.sharedValue); // 1

다음과 같이 사용할 수 있다.

간단히 설명하자면 Animal.prototype이라는 Object가 어딘가 존재하고, Animal 함수로부터 생성된 객체(dog,cat)들은 

어딘가에 존재하는 Object에 들어있는 값을 모두 갖다쓸 수 있다.

즉, say() 함수와 sharedValue를 어딘가에 넣어놓고 dog과 cat이 공유해서 사용하는 것이다. 

 

객체 생성자를 상속받는 방법

call 이라는 키워드를 사용해 객체 생성자를 상속받을 수 있다.

function Animal(type, name, sound) {
  this.type = type;
  this.name = name;
  this.sound = sound;
}

Animal.prototype.say = function () {
  console.log(this.sound);
};

function Dog(name, sound) {
  Animal.call(this, "개", name, sound);
}

function Cat(name, sound) {
  Animal.call(this, "고양이", name, sound);
}

Dog.prototype = Animal.prototype;
Cat.prototype = Animal.prototype;

const dog = new Dog("멍멍이", "멍멍");
const cat = new Cat("야옹이", "야옹");

dog.say(); // 멍멍
cat.say(); // 야옹

코드를 차례로 살펴보자.

먼저, Animal이라는 객체 생성자를 만들어 줬고 Animal.prototype에 say()라는 함수를 집어넣어주었다.

그다음 Dog라는 객체 생성자와 Cat이라는 객체 생성자를 만든다. 각 객체생성자는 call 키워드로 Animal 객체생성자를 상속받았는데 파라미터에는 해당 객체생성자를 뜻하는 this를 넣어주어야 한다.(여기서는 Dog와 Cat) 나머지

파라미터들은  상속받는 객체 생성자의 파라미터를 넣어준다. 

마지막으로 프로토타입을 Dog와 Cat도 공유하도록 해준다.

 

클래스(Class)

자바스크립트에서는 이전에 클래스라는 개념이 아예 없었다. 그래서 위의 코드와 같은 방법으로 구현을 했었다.

클래스라는 기능은 C++, Java, Python와 같은 언어에는 있는 기능이지만 자바스크립트에는 없었다.

하지만 ECMAScript6(ES6)에서 클래스라는 기능이 자바스크립트에도 추가되었다. 다른 언어에서의 클래스와 완전 

똑같은 것은 아니지만 위의 코드와 같은 작업을 보다 알기 쉬운 문법으로 작성할 수 있게 해 준다.

 

class Animal {
  constructor(type, name, sound){
    this.type = type;
    this.name = name;
    this.sound = sound;
  }

  say(){
    console.log(this.sound);
  }
}

const dog = new Animal('개', '멍멍이','멍멍');
const cat = new Animal('고양이', '야옹이','야옹');

dog.say() // 멍멍
cat.say() // 야옹

다음과 같이 클래스를 사용할 수 있다. 자바스크립트의 클래스에서는 객체 생성자와 비슷한 constructor가 있다. 생성자라는 의미로 constructor에서 파라미터를 받아온다.

 

 위의 코드에서 say() 함수를 클래스 내에서 구현했는데, 클래스 내에서 함수를 작성하면 자동으로 프로토타입으로 등록이 된다. 

console.log(Animal.prototype.say); // [Function: say]

 

또, 클래스를 사용하면 상속을 해야 하는 상황에서 훨씬 더 쉽게 상속을 받을 수 있다. 상속을 받는 클래스는

파라미터를 받아오는 constructor만 작성해주면 된다.   

 

class Animal {
  constructor(type, name, sound) {
    this.type = type;
    this.name = name;
    this.sound = sound;
  }

  say() {
    console.log(this.sound);
  }
}

class Dog extends Animal {
  constructor(name, sound) {
    super("개", name, sound);
  }
}

class Cat extends Animal {
  constructor(name, sound) {
    super("개", name, sound);
  }
}

const dog = new Dog("멍멍이", "멍멍");
const cat = new Cat("야옹이", "야옹");

dog.say(); // 멍멍
cat.say(); // 야옹

여기서 Dog와 Cat의 super는 Animal의 constructor를 뜻한다. 자신이 상속받은 클래스의 constructor를 호출하는 키워드가 바로 super인 것이다.

 

결국 클래스란 객체 생성자와 프로토타입을 좀 더 쉽게 사용하기 위해서 만들어진 문법이다.

반응형