[DevCamp] JavaScript에서 배우는 객체 지향과 메모리 관리

동건·2025년 4월 2일
0

DevCamp

목록 보기
39/85

JavaScript에서 배우는 객체 지향과 메모리 관리

프로그래밍 언어마다 다양한 개념이 존재하지만, 많은 개념이 공통적으로 사용된다.
오늘 학습한 내용을 JavaScript를 기반으로 프로그래밍의 핵심 개념을 정리하겠다.


1. 함수 포인터 (Function Pointer)

JavaScript에서는 함수도 객체이기 때문에,
함수 자체를 변수에 저장하고 다른 함수의 인자로 넘길 수 있다.

이를 함수 포인터 또는 고차 함수(Higher-Order Function) 개념으로 이해할 수 있다.

function greet(name) {
  console.log(`Hello, ${name}!`);
}

const sayHello = greet;  // 함수 포인터처럼 사용
sayHello("Alice"); // Hello, Alice!

2. 구조체 (Struct)

JavaScript에는 struct 키워드는 없지만,
객체를 활용하면 동일한 개념을 표현할 수 있다.

const person = {
  name: "John",
  age: 30,
  isStudent: false
};

console.log(person.name); // John

3. 공용체 & Enum

공용체(Union)는 C에서 동일한 메모리 공간을 공유하는 데이터 구조이지만,
JavaScript에서는 비슷한 개념이 없다.
하지만 TypeScriptUnion Type을 활용하면 비슷한 효과를 얻을 수 있다.

type ID = string | number; // 문자열 또는 숫자를 받을 수 있는 타입

let userId: ID = 123;
userId = "abc123";

Enum은 TypeScript에서 제공하며, 특정 값들을 열거할 때 유용하다.

enum Direction {
  Up,
  Down,
  Left,
  Right
}

const move = Direction.Up;
console.log(move); // 0

4. 동적 메모리 할당

JavaScript에서는 new 키워드로 객체를 생성할 수 있으며,
가비지 컬렉터(GC)가 자동으로 메모리를 관리한다.

class Person {
  constructor(name) {
    this.name = name;
  }
}

const p1 = new Person("Alice");

5. 객체 지향 프로그래밍 (OOP)

5.1 추상화 (Abstraction)

객체의 내부 구현을 숨기고, 필요한 기능만 외부에 제공하는 개념이다.

class Car {
  constructor(brand) {
    this.brand = brand;
  }
  
  startEngine() {
    console.log(`${this.brand}의 엔진을 시작합니다.`);
  }
}

const myCar = new Car("Tesla");
myCar.startEngine(); // Tesla의 엔진을 시작합니다.

5.2 캡슐화 (Encapsulation)

객체의 속성을 외부에서 직접 접근하지 못하게 하고,
메서드를 통해 조작하도록 하는 개념이다.

class BankAccount {
  #balance = 0; // private 속성

  deposit(amount) {
    this.#balance += amount;
  }

  getBalance() {
    return this.#balance;
  }
}

const account = new BankAccount();
account.deposit(1000);
console.log(account.getBalance()); // 1000

5.3 클래스의 기본 개념과 생성자 (Constructor)

클래스는 constructor를 사용해 초기화된다.

class Animal {
  constructor(name) {
    this.name = name;
  }

  makeSound() {
    console.log("Some sound...");
  }
}

6. 상속 (Inheritance)

클래스를 확장(extend)하여 기존 기능을 재사용할 수 있다.

class Dog extends Animal {
  makeSound() {
    console.log("Woof! Woof!");
  }
}

const myDog = new Dog("Buddy");
myDog.makeSound(); // Woof! Woof!

7. 오버로딩과 오버라이딩

7.1 오버로딩 (Overloading)

JavaScript는 명시적 오버로딩을 지원하지 않지만,
매개변수 개수에 따라 다르게 동작하는 방식으로 구현할 수 있다.

function add(a, b, c) {
  if (c !== undefined) return a + b + c;
  return a + b;
}

console.log(add(2, 3)); // 5
console.log(add(2, 3, 4)); // 9

7.2 오버라이딩 (Overriding)

상속받은 메서드를 자식 클래스에서 재정의하는 개념이다.

class Parent {
  sayHello() {
    console.log("Hello from Parent");
  }
}

class Child extends Parent {
  sayHello() {
    console.log("Hello from Child");
  }
}

const child = new Child();
child.sayHello(); // Hello from Child

8. 인터페이스 (Interface)

JavaScriptinterface 를 직접 지원하지 않지만,
TypeScript 에서 사용할 수 있다.

interface Animal {
  name: string;
  makeSound(): void;
}

class Dog implements Animal {
  name: string;
  
  constructor(name: string) {
    this.name = name;
  }

  makeSound() {
    console.log("Woof!");
  }
}

9. 람다 (Lambda)

람다(Lambda)는 화살표 함수(Arrow Function) 를 의미한다.

const add = (a, b) => a + b;
console.log(add(3, 4)); // 7

또한, map과 같은 함수형 프로그래밍에도 활용된다.

const numbers = [1, 2, 3];
const squared = numbers.map(num => num ** 2);
console.log(squared); // [1, 4, 9]

🔨 TIL

오늘은 객체 지향 프로그래밍과 메모리 관리 관련 개념을 JavaScript에서 어떻게 활용하는지 살펴보았다.
JavaScript는 명확한 객체 지향 언어는 아니지만,
다양한 패턴을 통해 이러한 개념을 구현할 수 있다.

추가로 TypeScript를 활용하면 더 강력한 타입 시스템을 적용할 수도 있다.

profile
배고픈 개발자

0개의 댓글