第11講

객체 기초

3 閲覧 1

객체 리터럴 문법, 프로퍼티 접근, 메서드 정의, this 바인딩을 이해한다. 동적 프로퍼티, 프로퍼티 단축, 계산된 프로퍼티명 등 현대적 객체 문법을 익힌다.

객체 — 관련 데이터를 묶는 컨테이너

객체는 키(key)와 값(value)의 쌍으로 데이터를 저장합니다. 배열이 순서 있는 목록이라면, 객체는 이름 있는 컬렉션입니다. 자바스크립트에서 배열, 함수, 날짜 등 거의 모든 것이 객체입니다.

객체 생성

// 객체 리터럴 (가장 일반적)
const person = {
  name: "Kim",
  age: 30,
  city: "Seoul"
};

// new Object() (잘 안 씀)
const person2 = new Object();
person2.name = "Lee";

// Object.create() (프로토타입 지정)
const proto = { greet() { return "Hello"; } };
const obj = Object.create(proto);

프로퍼티 접근

const user = { name: "Kim", age: 30, "user-role": "admin" };

// 점 표기법 (일반적)
user.name    // "Kim"
user.age     // 30

// 대괄호 표기법 (동적 키, 특수문자 포함 키)
user["name"]        // "Kim"
user["user-role"]   // "admin"
const key = "age";
user[key]           // 30 — 동적 접근

// 없는 프로퍼티
user.phone          // undefined (에러 아님)
user.phone.number   // TypeError — undefined의 프로퍼티 접근 불가!

// 안전한 접근
user?.phone?.number // undefined (옵셔널 체이닝)

프로퍼티 추가, 수정, 삭제

const obj = { a: 1 };

obj.b = 2;       // 추가
obj.a = 10;      // 수정
delete obj.b;    // 삭제

// 존재 여부 확인
"a" in obj              // true
obj.hasOwnProperty("a") // true
Object.hasOwn(obj, "a") // true (ES2022, 권장)

현대적 객체 문법

const name = "Kim";
const age = 30;

// 1. 프로퍼티 단축 (ES6)
const user = { name, age }; // { name: "Kim", age: 30 }

// 2. 계산된 프로퍼티명
const field = "score";
const record = {
  [field]: 90,          // { score: 90 }
  [`${field}_max`]: 100 // { score: 90, score_max: 100 }
};

// 3. 메서드 단축
const calculator = {
  value: 0,
  add(n) { this.value += n; return this; }, // 단축 표기
  subtract(n) { this.value -= n; return this; },
  result() { return this.value; }
};

calculator.add(10).add(5).subtract(3).result(); // 12 (체이닝)

메서드와 this

const circle = {
  radius: 5,
  // 메서드 — this가 circle을 가리킴
  area() {
    return Math.PI * this.radius ** 2;
  },
  circumference() {
    return 2 * Math.PI * this.radius;
  }
};

circle.area();          // 78.53...
circle.circumference(); // 31.41...

// this는 호출 방식에 따라 달라짐
const areaFn = circle.area;
areaFn(); // this가 undefined (strict mode) 또는 window

// 해결: bind
const boundArea = circle.area.bind(circle);
boundArea(); // 78.53...

Object 내장 메서드

const user = { name: "Kim", age: 30, city: "Seoul" };

// 키/값/엔트리 배열로 추출
Object.keys(user)    // ["name", "age", "city"]
Object.values(user)  // ["Kim", 30, "Seoul"]
Object.entries(user) // [["name","Kim"], ["age",30], ["city","Seoul"]]

// 반복 활용
Object.entries(user).forEach(([key, value]) => {
  console.log(`${key}: ${value}`);
});

// entries → Object 역변환
const entries = [["a", 1], ["b", 2]];
Object.fromEntries(entries); // { a: 1, b: 2 }

// 얕은 복사
const copy = Object.assign({}, user);
const copy2 = { ...user }; // 스프레드 (더 간결)

// 병합
const defaults = { theme: "light", lang: "ko" };
const userPrefs = { theme: "dark" };
const settings = { ...defaults, ...userPrefs };
// { theme: "dark", lang: "ko" } — 뒤쪽이 앞쪽 덮어씀

// 동결 (변경 불가)
const config = Object.freeze({ apiUrl: "https://api.example.com" });
config.apiUrl = "other"; // 무시됨 (에러 없음, strict mode에선 에러)

동적 객체 처리 패턴

// 조건부 프로퍼티 추가
const isAdmin = true;
const user = {
  name: "Kim",
  ...(isAdmin && { role: "admin", dashboard: "/admin" })
};
// { name: "Kim", role: "admin", dashboard: "/admin" }

// 특정 키 제거 (스프레드로)
const { password, ...safeUser } = { name: "Kim", age: 30, password: "secret" };
console.log(safeUser); // { name: "Kim", age: 30 }

// 키 이름 변환
const { name: displayName, age: userAge } = user;
console.log(displayName, userAge); // "Kim", 30

관련 검색어  ·  자바스크립트 객체, Object.keys values entries, 프로퍼티 단축, 계산된 프로퍼티명, 객체 복사 방법, Object.freeze

채용정보
공지사항
인사이트
MY