class > constructor 사용 이유

pioneerwing·2024년 5월 24일

JavaScript

목록 보기
3/3

constructor 사용 이유

constructor(생성자)는 클래스에서 객체를 생성할 때 호출되는 특별한 메서드이다. constructor를 사용하는 이유는 객체가 생성될 때 필요한 초기화 작업을 수행하기 위함이다.

1. constructor 있음

class FruitStoreWithConstructor {
    constructor(fruitName, quantity, color) {
        this.fruitName = fruitName;
        this.quantity = quantity;
        this.color = color;
    }

    displayInfo() {
        console.log(`This store sells ${this.quantity} ${this.color} ${this.fruitName}(s).`);
    }
}

// 생성자를 사용하여 인스턴스 생성
let fruitStoreWithConstructor = new FruitStoreWithConstructor("apple", 20, "red");
fruitStoreWithConstructor.displayInfo();

2. constructor 없음

class FruitStoreWithoutConstructor {
    setFruitInfo(fruitName, quantity, color) {
        this.fruitName = fruitName;
        this.quantity = quantity;
        this.color = color;
    }

    displayInfo() {
        console.log(`This store sells ${this.quantity} ${this.color} ${this.fruitName}(s).`);
    }
}

// 생성자를 사용하지 않고 인스턴스 생성
let fruitStoreWithoutConstructor = new FruitStoreWithoutConstructor();
fruitStoreWithoutConstructor.setFruitInfo("banana", 15, "yellow");
fruitStoreWithoutConstructor.displayInfo();

생성자를 사용하여 클래스를 생성하는 방법과 생성자를 사용하지 않고 클래스의 메서드를 통해 정보를 초기화하는 방법을 보여주었습니다. 생성자를 사용하면 객체 생성 시 초기화 과정이 간소화되고 코드의 가독성이 높아집니다.생성자 없이 클래스를 초기화하는 경우에는 객체를 생성한 뒤에 추가적인 메서드를 이용해 초기화를 수행해야합니다.

profile
I am korean.

0개의 댓글