코드 스테이츠 블로깅 : 클래스와 인스턴스

Rosevillage·2023년 1월 13일
0

클래스와 인스턴스 생성

자바스크립트에서 객체를 생성하는 함수를 생성자라고 부르고, 이 생성자를 바탕으로 만들어지는 객체를 인스턴스 객체라 부른다.

생성자 함수를 정의한 것을 팩토리얼 혹은 클래스라고 부르는데, 클래스를 new키워드와 함께 사용하면 비슷한 종류의 이름이 다르고, 같은 메서드를 공유하는 객체들을 만들 수 있다.

function Car(name, brand, color) {
  this.name = name;
  this.brand = brand;
  this.color = color;
}

let morning = new Car('morning', 'kia', 'yellow');
// morning이라는 이름과, kia라는 브랜드의, yellow색을 가지는 객체 생성

인스턴스는 어떻게 부모의 메서드를 사용할 수 있을까

이는 함수생성시 자동으로 만들어지는 prototype과 인스턴스들이 가지는 __proto__에 의해 가능해진다.

  • 함수를 생성하면 자바스크립트는 자동적으로 그 함수의 prototype을 생성한다.
  • prototype은 constructor로 함수를 가리키고
  • 함수의 [[prototype]]은 prototype을 가리킨다.
  • 함수로 인해 생성된 인스턴스는 내부에 __proto__라는 프로퍼티를 가지는데 이 프로퍼티는 prototype에 대한 참조를 가진다.
  • 메서드들은 prototype에 담겨지므로, 인스턴스들이 참조를 통해 prototype의 메서드를 가져와 사용할 수 있게 되는 것이다.

ES5, ES6 클래스 작성방식

ES6에서는 class라는 키워드를 추가했다. 이를 통해 기존 함수를 통해 클래스를 작성하는 방법뿐만 아니라 class를 사용해 클래스를 작성하는 방법이 생겨났다.

  • ES5
// 클래스(속성 포함) 정의
function Car(name, brand, color) {
  this.name = name;
  this.brand = brand;
  this.color = color;
}
// 매서드 정의
Car.prototype.refuel = function(){/*연료공급 구현*/}
Car.prototype.drive = function() {/*운전 구현*/}
// 인스턴스
let morning = new Car('morning', 'kia', 'yellow');

morning.drive(); // morning 운전 시작
  • ES6
// 클래스(속성 포함) 정의
class Car {
  constructor(name, brand, color) {
    this.name = name;
    this.brand = brand;
    this.color = color;
  }
  // 메서드 정의
  refuel() {/*연료공급 구현*/}
  
  drive() {/*운전 구현*/}
}
// 인스턴스
let spark = new Car('spark', 'chevbrolet', blue);

spark.refuel() // spark 연료 충전

클로저 모듈 패턴

같은 기능을 하는 객체가 여러개 필요할 때
예시) 똑같은 기능을 하는 카운터를 여러 개 만드는 방법 중 하나

function makeCounter() {
  let value = 0;
  return {
    increase: function() {
      value++;
    },
    decrease: function() {
      value--;
    },
    getValue: function() {
      return value;
    }
  }
}

let counter1 = makeCounter()
counter1.increase()
counter1.getValue() // 1

let counter2 = makeCounter()
counter2.decrease()
counter2.decrease()
counter2.getValue() // -2

참고 사이트
이미지: PoiemaWeb-Prototype

0개의 댓글