JavaScript Object


자바스크립트에서 객체(Object)는 속성(Property)과 메서드(Method)의 모음입니다. 객체는 데이터와 기능을 하나의 단위로 묶어서 구조화할 수 있도록 도와줍니다. 자바스크립트 객체에 대해 아주 상세히 설명하겠습니다.

1. 객체 생성

자바스크립트에서 객체를 생성하는 방법은 여러 가지가 있습니다.

1.1 객체 리터럴 (Object Literal)

객체 리터럴은 가장 간단하고 직관적인 객체 생성 방법입니다.

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

console.log(person.name); // Alice
person.greet(); // Hello, my name is Alice.

1.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 bob = new Person('Bob', 30);
console.log(bob.name); // Bob
bob.greet(); // Hello, my name is Bob.

1.3 Object.create() 메서드

Object.create() 메서드는 프로토타입 객체를 지정하여 새 객체를 생성합니다.

const personProto = {
  greet: function() {
    console.log(`Hello, my name is ${this.name}.`);
  }
};

const charlie = Object.create(personProto);
charlie.name = 'Charlie';
charlie.age = 28;

console.log(charlie.name); // Charlie
charlie.greet(); // Hello, my name is Charlie.

2. 객체의 속성

객체는 속성을 가지며, 속성은 키-값 쌍으로 구성됩니다.

2.1 속성 접근

속성에 접근하는 방법은 두 가지입니다.

  • 점 표기법 (Dot Notation)
  • 대괄호 표기법 (Bracket Notation)
const person = {
  name: 'Alice',
  age: 25
};

console.log(person.name); // Alice (점 표기법)
console.log(person['age']); // 25 (대괄호 표기법)

2.2 속성 추가 및 수정

객체의 속성은 동적으로 추가하거나 수정할 수 있습니다.

const person = {
  name: 'Alice',
  age: 25
};

person.city = 'Wonderland'; // 속성 추가
person.age = 26; // 속성 수정

console.log(person); // { name: 'Alice', age: 26, city: 'Wonderland' }

2.3 속성 삭제

delete 키워드를 사용하여 객체의 속성을 삭제할 수 있습니다.

const person = {
  name: 'Alice',
  age: 25,
  city: 'Wonderland'
};

delete person.city;

console.log(person); // { name: 'Alice', age: 25 }

3. 객체 메서드

객체 메서드는 객체에 정의된 함수입니다. this 키워드는 메서드 내부에서 객체 자신을 참조합니다.

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

person.greet(); // Hello, my name is Alice.

4. 객체의 프로토타입

자바스크립트는 프로토타입 기반 언어입니다. 객체는 다른 객체를 상속할 수 있으며, 이를 통해 코드 재사용이 가능합니다.

4.1 프로토타입 체인

객체는 __proto__ 또는 [[Prototype]]을 통해 다른 객체의 속성과 메서드를 상속받습니다.

const personProto = {
  greet: function() {
    console.log(`Hello, my name is ${this.name}.`);
  }
};

const alice = Object.create(personProto);
alice.name = 'Alice';

alice.greet(); // Hello, my name is Alice.

4.2 prototype 속성

함수 객체는 prototype 속성을 가지고 있으며, 이는 생성된 모든 인스턴스가 공유하는 프로토타입을 정의합니다.

function Person(name, age) {
  this.name = name;
  this.age = age;
}

Person.prototype.greet = function() {
  console.log(`Hello, my name is ${this.name}.`);
};

const bob = new Person('Bob', 30);
bob.greet(); // Hello, my name is Bob.

5. 객체의 내장 메서드

자바스크립트는 객체를 다루기 위한 다양한 내장 메서드를 제공합니다.

5.1 Object.keys()

객체의 모든 속성 키를 배열로 반환합니다.

const person = {
  name: 'Alice',
  age: 25,
  city: 'Wonderland'
};

console.log(Object.keys(person)); // ['name', 'age', 'city']

5.2 Object.values()

객체의 모든 속성 값을 배열로 반환합니다.

console.log(Object.values(person)); // ['Alice', 25, 'Wonderland']

5.3 Object.entries()

객체의 모든 속성 키-값 쌍을 배열로 반환합니다.

console.log(Object.entries(person)); // [['name', 'Alice'], ['age', 25], ['city', 'Wonderland']]

5.4 Object.assign()

하나 이상의 출처 객체로부터 대상 객체에 속성을 복사합니다.

const target = { a: 1, b: 2 };
const source = { b: 3, c: 4 };

const returnedTarget = Object.assign(target, source);

console.log(returnedTarget); // { a: 1, b: 3, c: 4 }

5.5 Object.freeze()

객체를 동결하여 속성을 추가, 수정, 삭제할 수 없도록 만듭니다.

const person = { name: 'Alice', age: 25 };
Object.freeze(person);

person.age = 30; // 무시됨
console.log(person); // { name: 'Alice', age: 25 }

5.6 Object.seal()

객체를 봉인하여 속성을 추가할 수 없고, 기존 속성의 구성 가능성을 변경할 수 없지만 속성 값을 수정할 수는 있습니다.

const person = { name: 'Alice', age: 25 };
Object.seal(person);

person.age = 30; // 수정 가능
delete person.name; // 무시됨
console.log(person); // { name: 'Alice', age: 30 }

6. 객체와 JSON

객체는 JSON(JavaScript Object Notation) 형식으로 직렬화하거나, JSON 문자열을 객체로 파싱할 수 있습니다.

6.1 JSON.stringify()

객체를 JSON 문자열로 변환합니다.

const person = { name: 'Alice', age: 25 };
const jsonString = JSON.stringify(person);

console.log(jsonString); // '{"name":"Alice","age":25}'

6.2 JSON.parse()

JSON 문자열을 객체로 변환합니다.

const jsonString = '{"name":"Alice","age":25}';
const person = JSON.parse(jsonString);

console.log(person); // { name: 'Alice', age: 25 }

7. 객체 지향 프로그래밍 (OOP)

자바스크립트는 객체 지향 프로그래밍 패러다임을 지원합니다.

7.1 클래스

ES6에서 도입된 클래스는 객체 지향 프로그래밍을 위한 문법적 설탕(Syntactic Sugar)입니다.

class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  greet() {
    console.log(`Hello, my name is ${this.name}.`);
  }
}

const dave = new Person('Dave', 35);
dave.greet(); // Hello, my name is Dave.

7.2 상속

클래스는 extends 키워드를 사용하여 상속할 수 있습니다.

class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  greet() {
    console.log(`Hello, my name is ${this.name}.`);
  }
}

class Student extends Person {
  constructor(name, age, grade) {
    super(name, age);
    this.grade = grade;
  }

  study() {
    console.log(`${this.name} is studying.`);
  }
}

const eve = new Student('Eve', 22, 'A');
eve.greet(); // Hello, my name is Eve.
eve.study(); // Eve is studying.

이상으로 자바스크립트의 객체에 대해 상세히 설명하였습니다. 객체는 자바스크립트의 핵심 개념 중 하나이며, 객체의 속성, 메서드, 프로토타입, 내장 메서드 등을 이해하면 더 효율적이고 구조적인 코드를 작성할 수


Leave a Reply

Your email address will not be published. Required fields are marked *