카테고리 없음

잊지말자 Javascript의 'New'

jimmmy_jin 2025. 2. 1. 21:19

🔹 new 키워드의 기능

new 키워드를 사용하면 새로운 인스턴스(객체) 가 생성되며, 다음과 같은 작업이 자동으로 수행된다.

  1. 새로운 객체를 생성 ({} 형태의 빈 객체가 내부적으로 만들어짐)
  2. 새로 생성된 객체를 this로 바인딩 (Product 생성자 내부에서 this가 새 객체를 가리킴)
  3. 생성자 함수(Product)를 실행 (this를 사용하여 해당 객체의 속성이 설정됨)
  4. 객체가 자동으로 반환됨 (명시적으로 return을 하지 않아도 새로운 객체가 반환됨)

🔹 new Product(...) 실행 과정 예제

아래처럼 Product라는 클래스(혹은 생성자 함수)가 있다고 가정해보자.

class Product {
  constructor(id, title, imageUrl, description, price) {
    this.id = id;
    this.title = title;
    this.imageUrl = imageUrl;
    this.description = description;
    this.price = price;
  }

  save() {
    console.log(`Saving product: ${this.title}`);
  }
}

이제 new Product(...)를 호출하면 내부에서 다음과 같은 동작이 일어난다:

const product = new Product(null, "Apple", "apple.jpg", "Fresh apple", 1.99);
  1. new 키워드가 실행되면서 {} 빈 객체가 생성됨.
  2. Product의 constructor가 실행되면서 this가 {} 빈 객체를 가리킴.
  3. this.id = null, this.title = "Apple", this.imageUrl = "apple.jpg", this.description = "Fresh apple", this.price = 1.99 속성이 객체에 추가됨.
  4. 최종적으로 새로 생성된 객체가 반환됨.

🔹 new 없이 호출하면?

만약 new 키워드를 생략하고 호출하면 this가 undefined 또는 global 객체(window 또는 globalThis)를 가리키게 되므로 예상과 다른 동작을 하게 된다.

const product = Product(null, "Apple", "apple.jpg", "Fresh apple", 1.99);
console.log(product); // undefined (오류 가능)

➡ new 없이 호출하면 Product 함수의 this가 제대로 바인딩되지 않기 때문에 오류가 발생할 수 있다.


🔹 정리

  • new 키워드는 생성자 함수(클래스)를 기반으로 새로운 객체를 생성하는 역할을 함.
  • new Product(...) 실행 시:
    • 새로운 객체 {}가 생성됨.
    • this가 새 객체를 가리키도록 설정됨.
    • Product 생성자가 실행되면서 객체의 속성이 초기화됨.
    • 생성된 객체가 자동으로 반환됨.
  • new 없이 호출하면 this가 제대로 설정되지 않아 오류가 발생할 수 있음.

즉, new Product(...)는 새로운 제품 객체를 생성하고, product.save()를 호출할 수 있도록 인스턴스를 반환하는 역할을 한다! 🚀