JavaScript

JavaScript 객체(Object)

bergerac 2025. 3. 29. 09:11

객체란? 

  • 정의: 관련된 **데이터(속성, 프로퍼티)**와 **함수(기능, 메서드)**를 하나로 묶은 집합입니다.
  • 역할: 다양한 값을 담을 수 있는 컨테이너이자, 동작을 포함한 구조체입니다.
  • 참고: 배열도 객체의 일종입니다. typeof [1, 2, 3]을 실행하면 결과는 object입니다.
console.log(typeof([1,2,3]));//object

 

객체의 구조

프로퍼티(Property)

객체가 가지는 데이터 입니다.

ex) 이름, 나이, 키, 직업 등

<객체의 구조>

let objectName = {
	키1: 값1,
	키2: 값2
    ...
}

<사람(Person)객체>

const person = {
  name: 'bergerac',
  age: 25,
  height: 179,
  speak: function() {
    console.log('안녕하세요!');
  }
};

 

객체 생성 방식

1> 객체 리터럴 방식

const person = {
  firstName: 'cyrano',
  lastName: 'bergerac',
  height: 179,
  hobby: ['sword', 'poet']
};
  • 키(key)는 문자열로 작성되며, 보통 따옴표는 생략합니다.
  • 값(value)은 숫자, 문자열, 배열, 함수, 다른객체 등 모든 타입이 가능합니다

2>생성자 함수 방식

비슷한 구조의 객체를 여러개 생성할 때 유용

function Human(name, height) {
  this.name = name;
  this.height = height;
  this.greet = function() {
    console.log(`Hello, ${this.name}`);
  };
}

const person1 = new Human('cyrano', 179);
const person2 = new Human('roxan', 157);

person1.greet(); // Hello, cyrano
person2.greet(); // Hello, roxan
  • this는 생생될 객체 자신을 가르킵니다.
  • new keyword를 통하여 객체가 생성됩니다.
  • 생성자 함수명은 UpperCamelCase 사용을 권장한다.

객체 멤버 접근 방식

객체의 각 요소는 키를 통하여 접근할 수 있습니다. 자바스크립트에서는 대표적으로 두가지 방법이 있습니다.

1>점표기법(dot notation)

가장 많이 사용하는 방식입니다.

object.key
object.method()

2> 대괄호 표기법(braket notation)

속성명이 문자열 형태일때 또는 동적으로 키를 설정할때 사용합니다.

object['key']
object['method']()

<예제: dog 객체>

let dog = {
  name: {
    last: 'choco',
    first: 'coco'
  },
  age: 3,
  color: 'white',
  favoriteToy: ['곰인형', '탱탱볼'],

  bark: function() {
    console.log('멍멍');
  },
  greet: function() {
    console.log(`Hello, ${this.name}`);
    console.log(`Hello, ${this.name.last}`);
  }
};

<점 표기법 예시>

console.log(dog.age);             // 3
console.log(dog.name.first);      // coco
console.log(dog.favoriteToy[1]);  // 탱탱볼

dog.greet();
// Hello, [object Object]
// Hello, choco

<대괄호 표기법 예시>

객체명['키']: 키값을 문자열로 전달

console.log(dog['age']); // 3

+)객체 프로퍼티 추가하기

객체명.프로퍼티명 = 값(데이터);
dog.speed = 10;
console.log(dog['speed']); // 10

 

this 키워드

자바스크립트에서 this는 지금 동작하고 있는 코드를 내포하고 있는 객체를 가르킨다.

1) 일반 함수의 this는 전역 컨텍스트(global context)를 의미한다.

function showThis() {
  console.log(this);
}

showThis(); // <ref *1> Object [global]

2)객체의 메서드 안의 this

객체의 변수에 할당되는 함수로 메서드 호출 시 this는 해당 메서드를 호출한 객체에 바인딩된다.(bind: 묶다 고정하다)

const myObject = {
  name: 'object',
  showThis: function() {
    console.log(this);
  }
}

myObject.showThis(); 
// { name: 'object', showThis: [Function: showThis] }
// >> myObject 즉, 메서드를 호출한 객체 그 자체가 출력

3)생성자 함수와 this

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

const person1 = new Person('cyrano');
const person2 = new Person('roxan');

console.log(person1.name); // cyrano
console.log(person2.name); // roxan

생성자 함수의 this는 새로 생성된 객체를 참조합니다. 

 

4) 화살표 함수와 this

const arrowObject = {
  name: 'object',
  showThis: () => {
    // '화살표 함수가 정의된 객체'의 생성 스코프를 this가 가져옴
    console.log(this);
  }
}

arrowObject.showThis(); // {}: global 전역 객체