1. 객체 지향 프로그래밍

  1 - 1) 객체 지향 프로그래밍이란 하나의 모델이 되는 청사진을 만들고 그 청사진을 바탕으로 한 객체를 만드는 프로그래밍 패턴이다.

  1 - 2) 이때 해당 청사진을 class라 하고 class의 객체를 instance라 한다.

  1 - 3) Instance는 new 키워드를 통해 생성될 수 있다.

  1 - 4) 자바스크립트는 원래 함수를 통해 class를 정의했으나 ES6 이후부터 자바와 같이 class 문법을 사용할 수 있게 되었다

  1 - 5) 둘의 동작 원리는 같다. 그냥 class 문법은 Syntatic sugar와 같다고 보면 된다.

  1 - 6) 클래스에서 우리가 나타내길 원하는 속성과 메소드 등을 정의할 수 있다.

 

2. ES5 vs ES6

  ES5와 ES6에서의 객체 지향 프로그래밍을 구현하는 방법을 예시 코드를 통해 살펴보자.

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
//ES5
function Car(brand, name, color) {
  this.brand = brand;
  this.name = name;
  this.color = color;
}
 
Car.prototype.refuel = function() {
  //연료 공급을 구현하는 코드
  //ES5에서는 class.prototype.method의 형식을 통해
  //해당 class의 method를 정의할 수 있다.
}
 
//ES6
class Car {
  constructor(brand, name, color) {
    this.brand = brand;
    this.name = name;
    this.color = color;
  }
  refuel() {
    //연료 공급을 구현하는 코드
    //ES6에서는 해당 클래스안에 바로 method를 만들어주면 된다
  }
}
cs

 

3. this? constructor?, prototype?

  3 - 1) this : 함수가 실행될 때, 해당 scope마다 생성되는 고유한 실행 context이다.

  즉 new 키워드를 통해 instance를 생성할 때 해당 인스턴스가 바로 this인 것이다.

  3 - 2) constructor : instance가 초기화될 때 생성하는 생성자 함수

  3 - 3) prototype : 모델의 청사진을 만들 때 쓰는 원형 객체이다.

 

 

4. 예시

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
function Car(brand, name, color) {
  this.brand = brand;
  this.name = name;
  this.color = color;
}
 
Car.prototype.drive = function () {
  console.log(
    `${this.brand}사의 ${this.color}색을 가진
    ${this.name}이 운전을 시작합니다`
  );
};
 
let avante = new Car("hyundai""avante""black");
//avante라는 instance를 생성
avante.drive();
//hyundai사의 black색을 가진
//avante가 운전을 시작합니다
//this는 avante를 가리킴
 
cs

 

 

5. 자바스크립트에서 배열

  왜 갑자기 배열 얘기를 꺼내나 할 수 있는데 사실 우리가 사용하는 배열은 이미

  자바 스크립트 내장 객체인 Array의 instance인 것이다!

  보통 배열을 선언할 때 [] 통해 선언하여 사용하지만 이런식으로도 가능하다.

  

1
2
let arr = new Array('1''2''3')
console.log(arr) // ['1', '2', '3']
cs

  때문에 배열에서 사용할 수 있는 .push(), .indexOf()와 같은 여러가지 기능들은 사실 Array 객체에 정의된 메소드인 것이다!

'Programming Language > Javascript' 카테고리의 다른 글

ES6 - Class(1)  (0) 2020.12.29
Rest Parameter & Spread Syntax  (0) 2020.11.06
Closure  (0) 2020.11.04
Scope  (0) 2020.11.04
2020/09/30 - JS - 반복문  (0) 2020.09.30

+ Recent posts