본문 바로가기
프로그래밍/JAVASCRIPT

자바스크립트에서 객체 이해하기

by AutoTechGuru 2023. 8. 20.
SMALL

 

자바스크립트에서 객체를 활용한 실용적인 예제

자바스크립트를 배우기 시작하면, 처음에는 다소 어려워 보일 수 있습니다. 그럼에도 불구하고 객체와 같은 기능은 코드를 깔끔하게 정리하고 재사용하기에 아주 유용합니다. 이 가이드에서는 객체를 어떻게 활용하는지 실용적인 예제를 통해 알아봅시다.

물건 판매 웹사이트 예제


const product = {
  name: '스마트폰',
  price: 1000000,
  category: '전자제품',
  details: {
    brand: '삼성',
    model: '갤럭시 S21',
    color: '검정'
  },
  showDetails: function() {
    console.log(`${this.name} - ${this.details.brand} ${this.details.model}, 가격: ${this.price}원`);
  }
};

const seller = {
  name: '이씨전자',
  location: '서울',
  products: [product],
  introduce: function() {
    console.log(`저희 ${this.name}에서 판매하는 제품입니다.`);
    this.products.forEach(product => product.showDetails());
  }
};

seller.introduce();
    

이 예제를 통해 자바스크립트에서 객체를 어떻게 활용할 수 있는지 구체적으로 알아보았습니다. 객체 안에 다른 객체를 넣거나 함수를 메서드로 활용하는 등 다양한 방법으로 코드를 구조화하고 활용할 수 있습니다.

LIST