
Object oriented programming Because you’ve got class 객체 지향 프로그래밍! 너는 클래스를 갖고 있으니
객체 지향 프로그래밍의 목적은 실세계의 복잡한 문제를 효과적으로 모델링하고 설계하는 것입니다. 이를 통해 코드의 재사용성, 확장성 및 유지 보수성이 향상됩니다. 근데 프론트엔드가 그런것도 알아야해? 라고 할 수 있습니다.
객체 지향 프로그래밍은 프론트엔드, 백엔드 구분 없이 작업할 수 있습니다. 장점이 많은 프로그래밍이라 언어에서 허용한다면 사용하는것이 좋고, 프론트엔드또한 객체지향 프로그래밍으로 재사용성을 높이고, 비즈니스 로직을 분리함에 유리할 수 있습니다.
Class와 그의 특성들
class에는 메소드와 그에 연결된 키워드들(private, protected, readonly)이 존재합니다. 우리는 그 키워드들과 메소드가 뭔지, 어떻게 사용하는지 하나하나 파악해 보도록 하겠습니다.
1. 기본적인 Class (FEAT. constructor란?)
JS에서 클래스를 정의하고 객체를 생성하는 방법은 다음과 같습니다.
class Animal { name: string; constructor(name: string) { this.name = name; } speak() { console.log(`${this.name} makes a sound.`); } } const dog = new Animal("Dog"); dog.speak(); // Dog makes a sound.
클래스의
constructor
는 클래스로부터 객체를 생성하고 초기화할 때 호출되는 특별한 메서드입니다. 클래스 내에 하나의 constructor
만 있어야 하며, 둘 이상의 constructor
를 포함하면 문법 오류가 발생합니다.TypeScript 예제:
TypeScript에서는
constructor
내부의 파라미터에 타입을 지정할 수 있습니다. 또한, 접근 제한자와 함께 사용하여 클래스의 속성을 바로 초기화하는 것도 가능합니다.class Animal { constructor(public name: string) { // name 속성이 바로 초기화됩니다. } } const cat = new Animal("Cat"); console.log(cat.name); // 출력: Cat
주의사항:
- 만약 클래스가 상속되는 경우, 파생 클래스의
constructor
는super()
를 호출하기 전에this
를 사용할 수 없습니다.super()
는 부모 클래스의constructor
를 참조하며, 이는 파생 클래스의constructor
내에서 먼저 호출되어야 합니다.
- TypeScript에서 클래스의 속성을 선언할 때, 해당 속성의 타입을 지정할 수 있습니다. 또한,
public
,private
,protected
와 같은 접근 제한자와readonly
키워드도 사용 가능합니다.
constructor
는 선택적으로 포함될 수 있습니다. 클래스에constructor
가 없는 경우, 기본constructor
가 제공됩니다.
이렇게
constructor
는 객체 지향 프로그래밍에서 중요한 역할을 하는 메서드로, 객체 생성과 초기화에 사용됩니다.2. Private, Protected, Public
TypeScript에서는
private
, protected
, public
이라는 접근 제어자를 제공합니다.public
(기본값): 어디서든지 접근 가능
private
: 클래스 내부에서만 접근 가능
protected
: 클래스 내부 및 파생된 클래스에서만 접근 가능
class Animal { public name: string; private type: string; protected habitat: string; constructor(name: string, type: string, habitat: string) { this.name = name; this.type = type; this.habitat = habitat; } getType() { return this.type; // 가능 } } class Bird extends Animal { fly() { console.log(`${this.name} flies in the ${this.habitat}.`); // habitat 접근 가능 } }
3. Readonly
readonly
키워드는 클래스의 속성이 생성자 내에서만 값이 할당될 수 있음을 나타냅니다.class Animal { readonly name: string; constructor(name: string) { this.name = name; } } const cat = new Animal("Cat"); cat.name = "Lion"; // 오류! readonly 속성은 재할당이 불가능하다.
4. 그 외의 Class 특성들
Static
클래스 레벨에서 공유되는 속성이나 메서드를 정의할 때 사용합니다.
class Helper { static PI = 3.141592; static calculateArea(radius: number) { return this.PI * radius * radius; } } console.log(Helper.calculateArea(5));
Abstract
추상 클래스는 직접 인스턴스화 할 수 없으며 파생된 클래스에서 구현되어야 합니다.
abstract class Shape { abstract getArea(): number; } class Circle extends Shape { constructor(public radius: number) { super(); } getArea() { return 3.141592 * this.radius * this.radius; } }
이렇게 클래스와 관련된 특성들은 객체 지향 프로그래밍을 효과적으로 지원하며, 코드의 안정성과 가독성을 높여줍니다.
이러한 객체지향 프로그램을 활용해 프론트엔드 관점에서 비즈니스 로직을 관리하고, 의존성 주입을 통해서 뷰 로직을 작성하면 완성도 있는 프로그래밍을 할 수 있고, 테스트에도 유용할 수 있습니다.