JavaScript에서 객체는 다양한 속성과 메서드를 포함하는 복합 데이터 구조입니다. 객체를 통해 데이터를 구조화하고 기능을 결합할 수 있습니다. 이 글에서는 객체의 생성, 속성 접근, 메서드 정의 등을 자세히 설명합니다.
1. 객체의 생성
객체 리터럴 사용
객체를 생성하는 가장 간단한 방법은 객체 리터럴을 사용하는 것입니다.
const person = {
name: 'John',
age: 30
};
Object 생성자 사용
Object 생성자를 사용하여 객체를 생성할 수도 있습니다.
const person = new Object();
person.name = 'John';
person.age = 30;
생성자 함수 사용
생성자 함수를 사용하여 객체를 생성할 수도 있습니다.
function Person(name, age) {
this.name = name;
this.age = age;
}
const person = new Person('John', 30);
2. 속성 접근
점 표기법
점 표기법을 사용하여 객체의 속성에 접근할 수 있습니다.
console.log(person.name); // John
console.log(person.age); // 30
대괄호 표기법
대괄호 표기법을 사용하여 객체의 속성에 접근할 수도 있습니다. 이 방법은 속성 이름에 공백이나 특수 문자가 있을 때 유용합니다.
console.log(person['name']); // John
console.log(person['age']); // 30
// 동적으로 속성에 접근할 때도 유용합니다.
const property = 'name';
console.log(person[property]); // John
3. 속성 추가 및 삭제
속성 추가
객체에 새로운 속성을 추가하는 방법은 매우 간단합니다.
person.gender = 'male';
console.log(person.gender); // male
속성 삭제
delete 연산자를 사용하여 객체의 속성을 삭제할 수 있습니다.
delete person.age;
console.log(person.age); // undefined
4. 메서드 정의
객체 리터럴로 메서드 정의
객체 리터럴을 사용하여 메서드를 정의할 수 있습니다.
const person = {
name: 'John',
age: 30,
greet: function() {
console.log('Hello, ' + this.name);
}
};
person.greet(); // Hello, John
ES6의 메서드 축약 구문
ES6부터는 메서드를 더 간단하게 정의할 수 있습니다.
const person = {
name: 'John',
age: 30,
greet() {
console.log('Hello, ' + this.name);
}
};
person.greet(); // Hello, John
생성자 함수에서 메서드 정의
생성자 함수 내부에서 메서드를 정의할 수도 있습니다.
function Person(name, age) {
this.name = name;
this.age = age;
this.greet = function() {
console.log('Hello, ' + this.name);
}
}
const person = new Person('John', 30);
person.greet(); // Hello, John
5. 객체의 속성 열거
for...in 문
for...in 문을 사용하여 객체의 모든 열거 가능한 속성을 반복할 수 있습니다.
for (let key in person) {
console.log(key + ': ' + person[key]);
}
// name: John
// age: 30
// greet: function() { ... }
Object.keys 메서드
Object.keys 메서드를 사용하여 객체의 모든 열거 가능한 속성 이름을 배열로 반환할 수 있습니다.
const keys = Object.keys(person);
console.log(keys); // ["name", "age", "greet"]
Object.values 메서드
Object.values 메서드를 사용하여 객체의 모든 열거 가능한 속성 값을 배열로 반환할 수 있습니다.
const values = Object.values(person);
console.log(values); // ["John", 30, function() { ... }]
Object.entries 메서드
Object.entries 메서드를 사용하여 객체의 모든 열거 가능한 속성 이름과 값을 배열의 배열로 반환할 수 있습니다.
const entries = Object.entries(person);
console.log(entries); // [["name", "John"], ["age", 30], ["greet", function() { ... }]]
6. 객체의 속성 정의와 제어
Object.defineProperty
Object.defineProperty 메서드를 사용하여 객체의 속성을 정의하고 제어할 수 있습니다.
const person = {};
Object.defineProperty(person, 'name', {
value: 'John',
writable: false, // 속성 값을 변경할 수 없음
enumerable: true, // 열거 가능
configurable: false // 속성을 삭제하거나 속성 설명자를 변경할 수 없음
});
console.log(person.name); // John
person.name = 'Doe';
console.log(person.name); // John (변경되지 않음)
Object.defineProperties
Object.defineProperties 메서드를 사용하여 여러 속성을 한 번에 정의할 수 있습니다.
Object.defineProperties(person, {
age: {
value: 30,
writable: true,
enumerable: true,
configurable: true
},
gender: {
value: 'male',
writable: true,
enumerable: true,
configurable: true
}
});
console.log(person.age); // 30
console.log(person.gender); // male
7. 객체의 프로토타입 상속
프로토타입 체인
JavaScript 객체는 프로토타입을 통해 상속을 구현합니다.
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.greet = function() {
console.log('Hello, ' + this.name);
};
const person = new Person('John', 30);
person.greet(); // Hello, John
Object.create
Object.create 메서드를 사용하여 새로운 객체를 생성하고, 특정 프로토타입을 설정할 수 있습니다.
const personPrototype = {
greet() {
console.log('Hello, ' + this.name);
}
};
const person = Object.create(personPrototype);
person.name = 'John';
person.greet(); // Hello, John
결론
JavaScript의 객체는 데이터와 기능을 구조화하는 강력한 도구입니다. 객체의 생성, 속성 접근, 메서드 정의, 속성 제어, 그리고 프로토타입 상속을 이해하면 더 효율적이고 유지보수 가능한 코드를 작성할 수 있습니다. 다양한 객체 메서드와 구문을 적절히 활용하여 JavaScript 프로그래밍을 더욱 능숙하게 다룰 수 있습니다.