JavaScript에서 객체 리터럴은 가장 흔하게 사용되는 객체 생성 방식입니다. 객체 리터럴을 사용하면 키와 값으로 구성된 프로퍼티를 갖는 객체를 쉽게 만들 수 있습니다. 이 방식은 {} 중괄호를 사용하여 객체를 직접 정의합니다.

객체 리터럴 생성

객체 리터럴은 중괄호 {} 안에 키: 값 쌍을 쉼표로 구분하여 나열함으로써 생성합니다. 키는 보통 문자열이고, 값은 어떤 JavaScript 데이터 타입도 될 수 있습니다(함수 포함).

 

예제:

const person = {
    name: "Alice",
    age: 25,
    isStudent: true,
    greet: function() {
        console.log('Hello, my name is ' + this.name);
    }
};

 

여기서 person 객체는 네 개의 프로퍼티를 가집니다:

  • name: 문자열
  • age: 숫자
  • isStudent: 불린
  • greet: 함수(메소드라고도 함)

프로퍼티 접근 방법

객체의 프로퍼티에 접근하기 위해서는 주로 두 가지 방법을 사용합니다: 점 표기법과 대괄호 표기법.

 

1. 점 표기법 (Dot notation)

  • 가장 일반적인 방법으로, 객체명.프로퍼티명을 사용하여 프로퍼티에 접근합니다.

예제:

console.log(person.name);  // "Alice"
person.greet();            // "Hello, my name is Alice"
const car = {
    make: "Toyota",
    model: "Corolla",
    year: 2021,
    displayInfo: function() {
        console.log(`Make: ${this.make}, Model: ${this.model}, Year: ${this.year}`);
    }
};
console.log(car.make);  // Toyota
console.log(car['model']);  // Corolla
car.displayInfo();  // Make: Toyota, Model: Corolla, Year: 2021

 

 

2. 대괄호 표기법 (Bracket notation)

  • 객체명['프로퍼티명']을 사용하여 접근합니다.
  • 프로퍼티 이름이 변수에 저장되어 있거나, 실행 시점에 결정되어야 하는 경우 유용합니다.

예제:

let property = 'name';
console.log(person[property]);  // "Alice"

property = 'age';
console.log(person[property]);  // 25

 

동적 프로퍼티 추가 및 삭제

JavaScript 객체는 유연하게 구성될 수 있습니다. 즉, 객체가 이미 생성된 후에도 새로운 프로퍼티를 추가하거나 기존 프로퍼티를 삭제할 수 있습니다.

  • 프로퍼티 추가
person.job = "Engineer";
console.log(person.job);  // "Engineer"

 

  • 프로퍼티 삭제
delete person.isStudent;
console.log(person.isStudent);  // undefined

 

예제:

const student = {
    name: "John",
    age: 22
};

// 새로운 프로퍼티 추가
student.major = "Computer Science";
console.log(student.major);  // Computer Science

// 프로퍼티 삭제
delete student.age;
console.log(student.age);  // undefined
const person = {
    firstName: "Emma",
    lastName: "Watson",
    fullName: function() {
        return `${this.firstName} ${this.lastName}`;
    },
    greet: function(greeting = "Hello") {
        console.log(`${greeting}, my name is ${this.fullName()}`);
    }
};

person.greet();  // Hello, my name is Emma Watson
person.greet("Hi");  // Hi, my name is Emma Watson

 

이러한 기능을 통해 객체는 프로그램 실행 중에 동적으로 변화하는 데이터를 효과적으로 관리할 수 있습니다. 객체 리터럴과 프로퍼티 접근 방법을 잘 이해하고 사용하는 것은 JavaScript 프로그래밍의 기본이며, 특히 웹 개발에서 중요한 역할을 합니다.

+ Recent posts