[250107] 어제는 콜백 지옥, 오늘은 클래스 지옥

김경민·2025년 1월 7일

TIL

목록 보기
13/64

오늘의 배운 내용입니다.

  • DOM
  • 클래스
  • 클로저

DOM의 기본 개념부터 JS를 통해 요소를 접근하고 제어하고 메서드, API를 사용해 DOM을 조작하는 방법부터 객체지향 프로그래밍 언어인 JS치고는 ES6부터 도입된 클래스 문법을 지나 상속을 배워 코드의 재사용성을 높히는 방법을 배우고 클로저 특성을 활용해 함수 상태를 캡슐화 한 후 정보 은닉을 구현하는 방법까지 배웠습니다.

1. DOM

DOM tree에 대해 이해하고
getElementById(), querySelector()와 같은 메서드를 통하여 DOM을 조작할 수 있습니다.

DOM tree는 HTML문서를 문서의 구조를 트리 형태로 표현한 것입니다. HTML 요소들이 트리 구조로 계층을 이루며, 부모-자식 관계가 형성됩니다. 예를 들어, html이 최상위 노드이고, headbody가 그 자식 노드로 존재합니다.

<html>
  <head>
    <title>웹 페이지</title>
  </head>
  <body>
    <h1>안녕하세요!</h1>
    <p>이것은 문단입니다.</p>
  </body>
</html>

DOM의 요소를 불러와 콜백하여 스크립트를 짤 수도 있습니다.

// DOM 요소 선택
const button = document.querySelector("button");
button.addEventListener("click", () => {
    alert("버튼이 클릭되었습니다!");
});

DOM의 button 요소를 querySelector()를 통하여 불러오고 콜백하여 클릭을 감지하는 코드가 완성 되었습니다.

2. 클래스

constructor로 인스턴스를 만들고, gettersetter로 속성을 제어할 수 있습니다. 또한, 상속을 통해 코드의 재사용성을 높일 수 있고, static method로 클래스에 직접 속하는 메서드를 정의할 수 있습니다.

class Person {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }
    introduce() {
        console.log(`안녕하세요, 저는 ${this.name}이고, 나이는 ${this.age}입니다.`);
    }
}
const person1 = new Person("김경민", 24);
person1.introduce();

2-1. 클래스 get과 set

gettersetter를 통하여 유효성 검사를 추가 할 수 있습니다.

class Person {
    constructor(name, age) {
        this._name = name;
        this._age = age;
    }
    get name() {
        return this._name;
    }
    set name(value) {
        if (!value) {
            console.log("이름을 입력해주세요!");
        } else {
            this._name = value;
        }
    }
    get age() {
        return this._age;
    }
    set age(value) {
        if (!value) {
            console.log("나이를 입력해주세요!");
        } else {
            this._age = value;
        }
    }
    introduce() {
        console.log(`안녕하세요, 저는 ${this._name}이고, 나이는 ${this._age}입니다.`);
    }
}
const person1 = new Person("김경민", 24);
person1.introduce();

_를 붙이는 이유는 value값을 계속 참조하여 무한정 검사하는 상황을 막기 위해서 입니다.

2-2. 클래스 상속

extends를 추가하여 부모 클래스로부터 상속을 받을 수 있습니다.

class Person {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }
    introduce() {
        console.log(`안녕하세요, 저는 ${this.name}이고, 나이는 ${this.age}입니다.`);
    }
}
class Student extends Person {
    constructor(name, age, studentId) {
        super(name, age);
        this.studentId = studentId;
    }
    introduce() {
        super.introduce();
        console.log(`학번은 ${this.studentId}입니다.`);
    }
}
const student1 = new Student("김철수", 21, "20230001");
student1.introduce();

super를 사용함으로 부모 클래스의 매개변수를 상속 받는 것입니다

2-3. 클래스 static

static키워드를 사용하여 클래스 안에 나만의 메서드를 만드는 방법입니다.

class calculator {
    static plus(a, b) {
        return a + b;
    }
    static minus(a, b) {
        return a - b;
    }
}
console.log(calculator.plus(5, 3)); // 8
console.log(calculator.minus(4, 6)); // -2

클래스 이름으로 직접 호출하여 메서드를 사용할 수 있습니다.

3. 클로저

함수와 그 함수가 선언된 환경을 기억하는 특성입니다.

function counter() {
    let num = 0;
    return function() {
        num++;
        console.log(num);
    };
}
const count1 = counter();
count1(); // 1
count1(); // 2

함수 안에서 선언된 함수는 재호출 되면 변수를 다시 선언해 무엇을 하든 변수가 재선언 되어 같은 값을 출력합니다.
이 증상을 해결하기 위해 변수를 함수 바깥에 두면 변수는 전역 변수가 되어 어느 곳에서든 변수를 수정할 권리가 생기는데 이를 막고 정보를 은닉하고자 사용되는게 JS의 클로저 특성입니다.

profile
김경민입니다.

0개의 댓글