JavaScript Objects
JavaScript Objects: 심층 분석과 활용 전략
JavaScript에서 **객체(Objects)**는 데이터와 기능을 구조화하는 기본 단위입니다. 객체는 속성(프로퍼티)과 메서드(함수)를 포함하여 복잡한 데이터를 쉽게 다룰 수 있게 해줍니다. 이 가이드는 JavaScript 객체의 기본 개념부터 고급 활용법까지 다양한 측면을 심층적으로 분석하고 전략적으로 접근하는 방법을 소개합니다.
1. 객체란?
- *객체(Object)**는 키-값 쌍으로 데이터를 저장하는 데이터 구조입니다. 각 키는 **프로퍼티(Property)**라고 불리며, 값은 다양한 데이터 타입(숫자, 문자열, 배열, 함수 등)을 가질 수 있습니다.
1.1. 객체의 중요성
- 데이터 구조화: 관련 데이터를 그룹화하여 관리하기 쉽게 만듭니다.
- 재사용성: 동일한 구조의 객체를 여러 번 사용할 수 있습니다.
- 캡슐화: 데이터와 기능을 하나의 단위로 묶어 외부로부터 숨길 수 있습니다.
- 유연성: 동적으로 프로퍼티를 추가, 수정, 삭제할 수 있습니다.
2. 객체 생성 방법
JavaScript에서는 여러 가지 방법으로 객체를 생성할 수 있습니다. 주요 생성 방법은 다음과 같습니다:
- 객체 리터럴(Object Literal)
- 생성자 함수(Constructor Function)
- 클래스(Class)
- Object.create() 메서드
2.1. 객체 리터럴(Object Literal)
가장 간단하고 직관적인 방법으로, 중괄호 {}
를 사용하여 객체를 생성합니다.
const person = {
name: "Alice",
age: 25,
greet() {
console.log(`Hello, my name is ${this.name}`);
}
};
console.log(person.name); // 출력: Alice
person.greet(); // 출력: Hello, my name is Alice
2.2. 생성자 함수(Constructor Function)
함수를 사용하여 객체의 틀을 정의하고, new
키워드를 통해 객체를 생성합니다.
function Person(name, age) {
this.name = name;
this.age = age;
this.greet = function() {
console.log(`Hello, my name is ${this.name}`);
};
}
const person1 = new Person("Bob", 30);
const person2 = new Person("Charlie", 35);
console.log(person1.name); // 출력: Bob
person2.greet(); // 출력: Hello, my name is Charlie
2.3. 클래스(Class)
ES6에서 도입된 class
문법을 사용하여 객체를 생성합니다. 생성자 함수보다 더 직관적이고 객체 지향 프로그래밍에 적합합니다.
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
console.log(`Hello, my name is ${this.name}`);
}
}
const person1 = new Person("Dave", 28);
const person2 = new Person("Eve", 32);
console.log(person1.age); // 출력: 28
person2.greet(); // 출력: Hello, my name is Eve
2.4. Object.create() 메서드
Object.create()
메서드를 사용하여 새로운 객체를 생성하며, 프로토타입을 지정할 수 있습니다.
const personPrototype = {
greet() {
console.log(`Hello, my name is ${this.name}`);
}
};
const person = Object.create(personPrototype);
person.name = "Frank";
person.age = 40;
console.log(person.name); // 출력: Frank
person.greet(); // 출력: Hello, my name is Frank
3. 객체의 프로퍼티와 메서드
객체는 프로퍼티와 메서드를 가질 수 있으며, 이를 통해 데이터를 저장하고 기능을 구현합니다.
3.1. 프로퍼티(Property)
프로퍼티는 객체의 속성을 나타내며, 키-값 쌍으로 구성됩니다.
const car = {
brand: "Toyota",
model: "Camry",
year: 2020
};
console.log(car.brand); // 출력: Toyota
console.log(car["model"]); // 출력: Camry
3.2. 메서드(Method)
메서드는 객체 내에서 정의된 함수로, 객체의 동작을 나타냅니다.
const car = {
brand: "Honda",
model: "Accord",
year: 2019,
startEngine() {
console.log(`${this.brand} ${this.model} engine started.`);
}
};
car.startEngine(); // 출력: Honda Accord engine started.
단축 문법:
ES6에서는 메서드를 더 간결하게 정의할 수 있습니다.
const car = {
brand: "Ford",
model: "Mustang",
year: 2021,
startEngine() {
console.log(`${this.brand} ${this.model} engine started.`);
}
};
car.startEngine(); // 출력: Ford Mustang engine started.
4. 객체의 프로퍼티 접근 및 수정
4.1. 프로퍼티 접근 방법
객체의 프로퍼티에 접근하는 방법은 두 가지가 있습니다: **점 표기법(Dot Notation)**과 대괄호 표기법(Bracket Notation).
4.1.1. 점 표기법(Dot Notation)
const person = {
name: "Alice",
age: 25
};
console.log(person.name); // 출력: Alice
console.log(person.age); // 출력: 25
4.1.2. 대괄호 표기법(Bracket Notation)
const person = {
name: "Bob",
age: 30
};
console.log(person["name"]); // 출력: Bob
console.log(person["age"]); // 출력: 30
4.2. 프로퍼티 수정 및 추가
객체의 프로퍼티는 언제든지 수정하거나 새로운 프로퍼티를 추가할 수 있습니다.
4.2.1. 프로퍼티 수정
const car = {
brand: "Toyota",
model: "Camry",
year: 2020
};
// 프로퍼티 수정
car.year = 2021;
console.log(car.year); // 출력: 2021
4.2.2. 새로운 프로퍼티 추가
const car = {
brand: "Toyota",
model: "Camry",
year: 2020
};
// 새로운 프로퍼티 추가
car.color = "Red";
console.log(car.color); // 출력: Red
4.3. 프로퍼티 삭제
delete
연산자를 사용하여 객체의 프로퍼티를 삭제할 수 있습니다.
const person = {
name: "Diana",
age: 28,
occupation: "Engineer"
};
// 프로퍼티 삭제
delete person.occupation;
console.log(person); // 출력: { name: "Diana", age: 28 }
5. 객체의 동적 속성 추가 및 삭제
JavaScript 객체는 생성 후에도 동적으로 프로퍼티를 추가하거나 삭제할 수 있습니다.
5.1. 동적 프로퍼티 추가
const book = {
title: "JavaScript Guide",
author: "Emily"
};
// 동적으로 프로퍼티 추가
book.publishedYear = 2022;
console.log(book.publishedYear); // 출력: 2022
5.2. 동적 프로퍼티 삭제
const book = {
title: "JavaScript Guide",
author: "Emily",
publishedYear: 2022
};
// 동적으로 프로퍼티 삭제
delete book.author;
console.log(book.author); // 출력: undefined
5.3. 대괄호 표기법을 이용한 동적 프로퍼티 추가/삭제
const user = {
username: "frank",
email: "frank@example.com"
};
const propName = "age";
// 동적으로 프로퍼티 추가
user[propName] = 35;
console.log(user.age); // 출력: 35
// 동적으로 프로퍼티 삭제
delete user[propName];
console.log(user.age); // 출력: undefined
6. 객체의 키와 값 다루기
JavaScript는 객체의 키와 값을 다양한 방식으로 다룰 수 있는 메서드를 제공합니다.
6.1. Object.keys()
객체의 모든 키를 배열로 반환합니다.
const car = {
brand: "Tesla",
model: "Model S",
year: 2021
};
const keys = Object.keys(car);
console.log(keys); // 출력: ["brand", "model", "year"]
6.2. Object.values()
객체의 모든 값을 배열로 반환합니다.
const car = {
brand: "Tesla",
model: "Model S",
year: 2021
};
const values = Object.values(car);
console.log(values); // 출력: ["Tesla
", "Model S", 2021]
6.3. Object.entries()
객체의 키-값 쌍을 배열의 배열 형태로 반환합니다.
const car = {
brand: "Tesla",
model: "Model S",
year: 2021
};
const entries = Object.entries(car);
console.log(entries);
// 출력: [["brand", "Tesla"], ["model", "Model S"], ["year", 2021]]
6.4. Object.fromEntries()
키-값 쌍의 배열을 객체로 변환합니다.
const entries = [["brand", "Tesla"], ["model", "Model S"], ["year", 2021]];
const car = Object.fromEntries(entries);
console.log(car);
// 출력: { brand: "Tesla", model: "Model S", year: 2021 }
7. 객체의 반복문
객체의 프로퍼티를 반복문을 사용하여 순회할 수 있습니다. 대표적인 반복문으로는 for...in
과 Object.keys()
,
Object.values()
, Object.entries()
를 활용한 방법이 있습니다.
7.1. for...in
반복문
for...in
반복문은 객체의 모든 열거 가능한 프로퍼티를 순회합니다.
const person = {
name: "George",
age: 40,
occupation: "Developer"
};
for (let key in person) {
console.log(`${key}: ${person[key]}`);
}
// 출력:
// name: George
// age: 40
// occupation: Developer
7.2. Object.keys()
, Object.values()
, Object.entries()
와 forEach
const car = {
brand: "BMW",
model: "X5",
year: 2021
};
// Object.keys()
Object.keys(car).forEach(key => {
console.log(`${key}: ${car[key]}`);
});
// Object.values()
Object.values(car).forEach(value => {
console.log(value);
});
// Object.entries()
Object.entries(car).forEach(([key, value]) => {
console.log(`${key}: ${value}`);
});
8. 객체의 내장 메서드
JavaScript는 객체를 다루기 위한 다양한 내장 메서드를 제공합니다. 이들 메서드는 객체의 프로퍼티를 관리하고 조작하는 데 유용합니다.
8.1. Object.assign()
두 개 이상의 객체를 하나의 객체로 병합합니다. 기존 객체는 수정되지 않고, 새로운 객체가 반환됩니다.
const target = { a: 1, b: 2 };
const source = { b: 3, c: 4 };
const merged = Object.assign({}, target, source);
console.log(merged); // 출력: { a: 1, b: 3, c: 4 }
주의사항:
- 얕은 복사(shallow copy)만 수행하므로, 중첩된 객체는 참조를 공유합니다.
8.2. Object.freeze()
객체를 동결하여 프로퍼티의 추가, 수정, 삭제를 방지합니다.
const config = {
apiEndpoint: "<https://api.example.com>",
timeout: 5000
};
Object.freeze(config);
config.timeout = 3000; // 변경되지 않음
console.log(config.timeout); // 출력: 5000
config.newProp = "test"; // 추가되지 않음
console.log(config.newProp); // 출력: undefined
8.3. Object.seal()
객체의 프로퍼티를 잠그지만, 기존 프로퍼티의 값을 수정할 수 있습니다. 프로퍼티의 추가나 삭제는 불가능합니다.
const user = {
name: "Helen",
age: 29
};
Object.seal(user);
user.age = 30; // 수정 가능
console.log(user.age); // 출력: 30
user.gender = "female"; // 추가되지 않음
delete user.name; // 삭제되지 않음
console.log(user.gender); // 출력: undefined
console.log(user.name); // 출력: Helen
8.4. Object.isFrozen()
, Object.isSealed()
객체가 동결되었는지 또는 봉인되었는지를 확인합니다.
const obj = {};
console.log(Object.isFrozen(obj)); // 출력: false
console.log(Object.isSealed(obj)); // 출력: false
Object.freeze(obj);
console.log(Object.isFrozen(obj)); // 출력: true
console.log(Object.isSealed(obj)); // 출력: true
8.5. Object.getPrototypeOf()
와 Object.setPrototypeOf()
객체의 프로토타입을 가져오거나 설정할 수 있습니다.
const animal = {
type: "Animal",
speak() {
console.log("Animal sound");
}
};
const dog = {
name: "Buddy"
};
Object.setPrototypeOf(dog, animal);
console.log(Object.getPrototypeOf(dog) === animal); // 출력: true
dog.speak(); // 출력: Animal sound
9. 프로토타입과 상속
JavaScript는 프로토타입 기반의 상속을 사용하여 객체 간에 속성과 메서드를 공유합니다. 프로토타입과 상속 개념을 이해하면 더 효율적이고 재사용 가능한 코드를 작성할 수 있습니다.
9.1. 프로토타입(Prototype)
모든 JavaScript 객체는 내부적으로 [[Prototype]]
이라는 속성을 가지며, 이를 통해 다른 객체의 속성과 메서드를 상속받을 수 있습니다.
const animal = {
type: "Animal",
speak() {
console.log("Animal sound");
}
};
const dog = Object.create(animal);
dog.name = "Max";
console.log(dog.type); // 출력: Animal
dog.speak(); // 출력: Animal sound
9.2. 프로토타입 체인(Prototype Chain)
프로토타입 체인은 객체가 프로토타입을 통해 다른 객체의 속성과 메서드를 상속받는 구조를 말합니다. 이 체인을 통해 상위 프로토타입의 속성과 메서드에 접근할 수 있습니다.
const grandparent = {
ancestry: "Grandparent",
greet() {
console.log("Hello from grandparent");
}
};
const parent = Object.create(grandparent);
parent.ancestry = "Parent";
const child = Object.create(parent);
child.ancestry = "Child";
console.log(child.ancestry); // 출력: Child
child.greet(); // 출력: Hello from grandparent
9.3. prototype
속성
함수는 자신만의 prototype
속성을 가지며, 이를 통해 생성된 객체가 상속받을 프로토타입을 설정할 수 있습니다.
function Person(name) {
this.name = name;
}
Person.prototype.greet = function() {
console.log(`Hello, my name is ${this.name}`);
};
const person1 = new Person("Ivy");
person1.greet(); // 출력: Hello, my name is Ivy
9.4. 상속(Inheritance) 구현
ES6 클래스 문법을 사용하여 상속을 구현할 수 있습니다.
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
}
class Dog extends Animal {
constructor(name, breed) {
super(name);
this.breed = breed;
}
speak() {
console.log(`${this.name} barks.`);
}
}
const dog = new Dog("Buddy", "Golden Retriever");
dog.speak(); // 출력: Buddy barks.
console.log(dog.breed); // 출력: Golden Retriever
10. JSON과 객체
JavaScript Object Notation(JSON)은 데이터를 교환하기 위한 표준 포맷으로, 객체와 배열을 텍스트 형태로 표현합니다. JSON을 사용하여 데이터를 직렬화(serialization)하고 역직렬화(deserialization)할 수 있습니다.
10.1. 객체를 JSON으로 변환
JSON.stringify()
메서드를 사용하여 객체를 JSON 문자열로 변환할 수 있습니다.
const user = {
name: "Jack",
age: 30,
hobbies: ["reading", "gaming"]
};
const jsonString = JSON.stringify(user);
console.log(jsonString);
// 출력: {"name":"Jack","age":30,"hobbies":["reading","gaming"]}
10.2. JSON을 객체로 변환
JSON.parse()
메서드를 사용하여 JSON 문자열을 객체로 변환할 수 있습니다.
const jsonString = '{"name":"Karen","age":25,"hobbies":["cycling","swimming"]}';
const user = JSON.parse(jsonString);
console.log(user.name); // 출력: Karen
console.log(user.hobbies); // 출력: ["cycling", "swimming