JS의 객체 지향

JavaScript에서 거의 모든 것이 객체이다.

JavaScript의 특이한 점:

  • 배열, 함수, 심지어 Date, RegExp 등도 모두 객체
  • 하지만 원시 타입은 객체가 아님: number, string, boolean, null, undefined

객체 지향 방법들:

1. 클래스 방식 (ES6+, 최신):

class Counter {
    constructor(initialValue = 0) {
        this.count = initialValue;
        this.history = [];
    }
    
    increment() {
        this.count++;
        this.addToHistory("+1");
    }
    
    decrement() {
        this.count--;
        this.addToHistory("-1");
    }
    
    addToHistory(action) {
        this.history.push({
            action: action,
            result: this.count,
            time: new Date().toLocaleTimeString()
        });
    }
}

// 사용
const myCounter = new Counter(0);
myCounter.increment();
console.log(myCounter.count);  // 1

2. 생성자 함수 방식 (예전 방식):

function Counter(initialValue) {
    this.count = initialValue || 0;
    this.history = [];
}

Counter.prototype.increment = function() {
    this.count++;
    this.addToHistory("+1");
};

Counter.prototype.addToHistory = function(action) {
    this.history.push({
        action: action,
        result: this.count,
        time: new Date().toLocaleTimeString()
    });
};

3. 객체 리터럴 방식:

const counterFactory = {
    create(initialValue = 0) {
        return {
            count: initialValue,
            history: [],
            increment() {
                this.count++;
                this.addToHistory("+1");
            },
            addToHistory(action) {
                this.history.push({
                    action: action,
                    result: this.count,
                    time: new Date().toLocaleTimeString()
                });
            }
        };
    }
};

상속도 가능:

class AdvancedCounter extends Counter {
    constructor(initialValue, maxValue) {
        super(initialValue);
        this.maxValue = maxValue;
    }
    
    increment() {
        if (this.count < this.maxValue) {
            super.increment();
        }
    }
}

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *