소개
컴퓨터 프로그래밍은 컴퓨터가 이해할 수 있는 언어를 사용해 컴퓨터에게 지시를 전달하는 것을 말합니다.
복잡도가 가장 낮은(오로지 숫자 0과 1로만 구성된) machine language가 있고, 반대로 가장 복잡하지만, 사람 언어와 가장 가까운 high-level language가 있습니다. 그리고 둘 사이에 중간 복잡도의 assembly language가 있습니다.
JavaScript도 가장 높은 복잡도를 갖는 high-level language에 속한다. high-level language를 좀 더 세분화해보면,
절차(process) 순서가 중심적인 procedural language와 object-oriented language로 나눌 수 있습니다. object-oriented language에 대해 아래에서 더 자세히 살펴보겠습니다.
Object-oriented (객체지향) JavaScript
객제 지향 프로그래밍이란 모델이 되는 청사진(blueprint)를 하나 만들고, 그 청사진을 바탕으로 여러개의 객체(object)를 만드는 프로그래밍 패턴입니다. 여기서 청사진이 곧 class가 되고 객체는 instance가 됩니다.
마치 빵 굽는 틀이 있는데 레서피에 따라 모양은 같지만 맛이나 색깔이 다른 빵을 만들어내는 것과 비슷하다고 볼 수도 있겠습니다.
Class와 Instance에 대한 예제
car라는 blueprint이자 곧 class는 instance에 적용될 어떤 '틀'을 정의만 해주고, 실제 사용은 instance가 합니다.
ES6에서는 class라는 키워드를 이용해 정의할 수 있습니다.
class Car { //class Car의 첫 글자(C)는 항상 대문자로 표기합니다.
constructor(brand, name, color) {
this.brand = brand; //new 키워드를 이용해 생성된 인스턴스가 this의 값이 됩니다.
this.name = name;
this.color = color;
}
}
Car라는 클래스는 brand, name, color와 같은 고유한 속성이 부여됐습니다.
이제 메소드를 부여해보겠습니다. 클래스에서 정의한 속성과 메소드는 인스턴스에서 사용할 수 있습니다.
Car.prototype.drive = function() {
console.log(this.name + ' 출발!'); //이제 dirve라는 메소드는 Car 클래스에 속한 모든 인스턴스도 갖게됩니다.
}
이제 new 키워드를 이용해 인스턴스를 만들어보겠습니다.
let avante = new Car("hyundai", "avante", "red");
//let으로 선언한 avante가 class Car의 instance입니다.
avante.brand // "hyundai"가 나옵니다.
avante.color // "red"
avante.drive(); // avante 출발!
속성과 달리 메소드는 함수이기 때문에 ()가 있어야 실행이 되는 것을 볼 수 있습니다.
위의 예제를 정리해보면, class인 Car는 drive라는 메소드(method/behavior)와 brand, name, color라는 속성(attributes/properties)을 갖고 있습니다.
class Car | name of class |
brand; name; color; | properties/attributes |
drive() | methods |
OOP Basic Concepts and its Benefits
- Encapsulation - 객체화 시켜서 변수 하나에 모두 담는 경우
- reduces complexity & increases reusability
- Inheritance - 부모 노드가 갖고 있는 속성을 자식이 상속받는 경우
- reduces complexity & isolates impact of changes (of what?)
- Abstraction - 추상화.. 실행되는 어떤 기능의 내부 구조, 실행 과정을 사용자가 알지 못해도 기능을 사용할 수 있는 경우
- eliminates redundant code
- Polymorphism - "여러가지 형태"를 의미하며 inheritance와 연관되는 부분도 있다.
- refactors ugly switch/case statements
'LearningJavaScript' 카테고리의 다른 글
Asynchronous & Promise (0) | 2020.09.21 |
---|---|
Object Oriented Programming & Prototype Chain (TIL) (0) | 2020.09.10 |
C.S. [Data Structure] Stack, Queue (0) | 2020.09.03 |
C.S. [Data Structure] Intro (4) | 2020.09.03 |
node.js 그리고 설치방법 (0) | 2020.08.31 |