Section 2 클래스와 인스턴스

44523·2023년 1월 13일

JavaScript 개념 정리

목록 보기
1/4

객체 지향

절차 지향 프로그래밍과는 다르게 데이터와 기능을 한곳에 묶어서 처리

속성과 메서드가 하나의 ‘객체’라는 개념에 포함되며 이는 자바스크립트 내장 타입인 object와는 다르게 클래스(Class)라는 이름으로 부른다.

  • 클로저 모듈 패턴의 차이 @메서드 호출 방식을 이용할 때에는 화살표 함수를 쓰지 않습니다.

카운터를 구현한 예제

let counter1 = {
  value: 0,
  increase: function() {
    this.value++ // 메서드 호출을 할 경우, this는 counter1을 가리킵니다
  },
  decrease: function() {
    this.value--
  },
  getValue: function() {
    return this.value
  }
}

counter1.increase()
counter1.increase()
counter1.increase()
counter1.decrease()
counter1.getValue() // 2

클로저 모듈 패턴을 이용한 예제


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

클래스

하나의 모델이 되는 청사진(instance object), ES6에서 새로운 문법이 도입됨

클래스는 대문자로 시작하여 일반명사로 일반적인 함수는 동사, 소문자로 만든다

function Car(brand, name, color) {
  // 인스턴스가 만들어질 때 실행되는 코드
}
//ES5

class Car {
  constructor(brand, name, color) {
    // 인스턴스가 만들어질 때 실행되는 코드
  }
}
//ES6

ES5 vs ES6

ES6 방식

class Car {
  constructor(brand, name, color) {
	// 인스턴스가 생성될 때 실행되는 코드(constructor: 생성자 함수)
    this.brand = brand;
    this.name = name;
    this.color = color;
  }
  refule() {
    return `${this.name}에 연료를 공급합니다.`
  }
  drive() {
    return `${this.name}가 운전을 시작합니다.`
  }
}

let avante = new Car('hyundai', 'avante', 'blue');
// avante 인스턴스는 Car라는 클래스의 고유한 속성과 메소드를 갖는다

console.log(avante) // Car { brand: 'hyundai', name: 'avante', color: 'blue' }
console.log(avante.brand) // hyundai
console.log(avante.name) // avante
console.log(avante.color) // blue
console.log(avante.refule()) // avante에 연료를 공급합니다.
console.log(avante.drive()) // avante가 운전을 시작합니다.

ES5 방식

 function Car(brand, name, color) {
    this.brand = brand;
    this.name = name;
    this.color = color;
  }
  Car.prototype.refule = function() {
	 `${this.name}에 연료를 공급합니다.`
  }
	Car.prototype.refule = function() {
	 `${this.name}가 운전을 시작합니다.`
  }

let avante = new Car('hyundai', 'avante', 'blue');

용어 정리

  • 인스턴스

청사진을 바탕으로 한 객체(object), new 키워드를 사용하며 즉시 생성자 함수가 실행, 변수에 클래스의 설계를 가진 새로운 객체. 즉 인스턴스가 할당되며 각각의 인스턴스는 클래스의 고유한 속성과 메서드를 갖게 된다.

  • new 키워드

새로운 인스턴스를 만드는 방법

  • 생성자 함수(constructor)

인스턴스가 만들어질 때 실행되는 코드 @생성자 함수는 return 값을 만들지 않는다.

  • 낮선 용어 정리

prototype : 모델의 청사진을 만들 때 쓰는 원형 객체(original form)

constructor : 인스턴스가 초기화될 때 실행하는 생성자 함수

this : 함수가 실행될 때, 해당 scope마다 생성되는 고유한 실행 context (execution context)이며 new 키워드로 인스턴스를 생성했을 때에는 해당 인스턴스가 바로 this의 값이 됨

0개의 댓글