JS/Javascript

[javascript] 객체 7 / 객체 내장 메서드

ui-o 2025. 9. 2. 17:11
반응형

객체 속성 관련 메서드

Object.keys(obj)

  • 객체의 자신의 속성(열거 가능한 속성) 키배열로 반환
  • 상속받은 속성은 제외됨.
  • 속성 순서는 추가된 순서를 따름
// [문법]
Object.keys(객체)
const user = { name: "Alice", age: 25 };
console.log(Object.keys(user)); // ["name", "age"]

Object.values(obj)

  • 객체의 자신의 값(value)만 배열로 반환.
// [문법]
Object.values(객체)
console.log(Object.values(user)); // ["Alice", 25]

Object.entries(obj)

  • 객체의 [키, 값] 쌍을 2차원 배열로 반환.
// [문법]
Object.entries(객체)
console.log(Object.entries(user)); // [["name", "Alice"], ["age", 25]]

Object.hasOwn(obj, prop) / obj.hasOwnProperty(prop)

  • 해당 속성이 객체 자신의 속성인지 확인
// [문법]
Object.hasOwn(객체, "속성명") // true/false

객체.hasOwnProperty("속성명") // true/false
console.log(user.hasOwnProperty("name")); // true
console.log(Object.hasOwn(user, "toString")); // false, 상속된 속성

객체 병합 및 복제 관련 메서드

Object.assign(target, ...sources)

  • 여러 객체의 속성을 대상 객체 또는 빈 객체에 복사, 얕은 복사
  • 얕은 복사임 → 중첩 객체는 참조만 복사됨.
// [문법 - 대상 객체에 복사하는 경우]
Object.assign(대상객체, 원본객체1, 원본객체2, ...)

// [문법 - 빈 객체에 복사하는 경우]
Object.assign({}, 원본객체1, 원본객체2, ...)

빈 객체에 복사하는 경우

  • 대상 객체 {} → 빈 객체, 기존 속성 없음
  • 빈 객체를 대상으로 하면 원본 객체를 직접 변경하지 않고 새 객체 생성 가능
const obj1 = { a: 1 };
const obj2 = { b: 2 };
const obj3 = Object.assign({}, obj1, obj2);
console.log(obj3); // {a:1, b:2}

Object.create(proto)

  • 주어진 프로토타입 객체(proto)를 갖는 새 객체 생성.
// [문법]
Object.create(프로토타입객체)
const parent = { greet() { console.log("Hi"); } };
const child = Object.create(parent);
child.greet(); // "Hi" → 상속됨

structuredClone(obj)

  • 객체를 깊은 복사
// [문법]
structuredClone(객체)
const original = { a: { b: 1 } };
const copy = structuredClone(original);
copy.a.b = 2;
console.log(original.a.b); // 1 → 깊은 복사

객체 속성 정의 및 제어

Object.defineProperty(obj, prop, descriptor)

  • 객체 속성을 정의하고 속성 설정(writable, enumerable, configurable) 가능.
// [문법]
Object.defineProperty(객체, "속성명", {
  value: 값,
  writable: true/false,     // 수정 가능 여부
  enumerable: true/false,   // 열거 가능 여부
  configurable: true/false  // 속성 삭제/재정의 가능 여부
})
const user = {};
Object.defineProperty(user, "name", {
  value: "Alice",
  writable: false,
  enumerable: true,
  configurable: true
});
console.log(user.name); // "Alice"
user.name = "Bob"; // 무시됨, writable: false

Object.defineProperties(obj, descriptors)

  • 여러 속성을 한 번에 정의 가능.
// [문법]
Object.defineProperties(객체, {
  "속성명1": { value: 값1, writable: true/false, ... },
  "속성명2": { value: 값2, writable: true/false, ... }
})
Object.defineProperties(user, {
  age: { value: 25, writable: true },
  city: { value: "Seoul", writable: false }
});

Object.getOwnPropertyDescriptor(obj, prop)

  • 속성의 상세 정보 반환
// [문법]
Object.getOwnPropertyDescriptor(객체, "속성명")
let user = {
  value: 25,
};

console.log(Object.getOwnPropertyDescriptor(user, 'value'));
// { value: 25, writable: true, enumerable: true, configurable: true }

Object.freeze(obj)

 

  • 객체 완전 동결 (속성 변경, 삭제, 추가 불가)
// [문법]
Object.freeze(객체)
let user = {
  value: 25,
};

Object.freeze(user);
user.value = 30; // 무시됨
delete user.value; // 무시됨
console.log(user); // { value: 25 }

Object.seal(obj)

  • 객체 밀봉 (속성 추가 불가, 기존 값은 수정 가능)
// [문법]
Object.seal(객체)
let user = {
  age: 30,
  value: 't',
};

Object.seal(user);
user.age = 20;  // 수정 가능
user.gender = 'male'; // 추가 불가

console.log(user); // { age: 20, value: 't' }

 객체 비교 및 판별 

Object.is(value1, value2)

  • 두 값이 동일한지 비교 (===와 유사하지만 NaN, -0 처리 다름)
// [문법]
Object.is(값1, 값2)
console.log(Object.is(NaN, NaN)); // true
console.log(Object.is(-0, +0)); // false

Object.prototype.toString.call(value)

 

  • 값의 정확한 타입 확인 → [object Type]
// [문법]
Object.prototype.toString.call(값)
// // 예제 1
console.log(Object.prototype.toString.call([])); // [object Array]
console.log(Object.prototype.toString.call({})); // [object Object]


// 예제 2
let user = {
  age: 30,
  value: 't',
};
console.log(Object.prototype.toString.call(user)); // [object Object]
console.log(Object.prototype.toString.call(user.age)); // [object Number]
console.log(Object.prototype.toString.call(user.value)); // [object String]

 

 

  • 두 값이 동일한지 비교 (===와 유사하지만 NaN, -0 처리 다름)
// [문법]
Object.is(값1, 값2)
console.log(Object.is(NaN, NaN)); // true
console.log(Object.is(-0, +0)); // false

객체 확장성 및 상속 관련

Object.getPrototypeOf(obj)

Object.setPrototypeOf(obj, proto)

  • 객체의 프로토타입을 가져오거나 변경
// [문법 - 반환]
Object.getPrototypeOf(객체)      // 객체의 프로토타입 반환

// [문법 - 설정]
Object.setPrototypeOf(객체, proto) // 객체의 프로토타입 설정
const parent = { hello: () => "hi" };
const child = {};
Object.setPrototypeOf(child, parent);
console.log(Object.getPrototypeOf(child) === parent); // true

Object.isExtensible(obj)

Object.preventExtensions(obj)

  • 객체에 새 속성 추가 가능 여부 확인 및 방지
// [문법 - 새 속성 추가 가능 여부 확인]
Object.isExtensible(객체)       

// [문법 - 새 속성 추가 불가]
Object.preventExtensions(객체)

 

console.log(Object.isExtensible(user)); // true
Object.preventExtensions(user);
user.newProp = 123; // 추가되지 않음

용도에 따른 분류

  • eys, values, entries → 속성 정보 확인
  • assign, create, structuredClone → 객체 복제/병합
  • defineProperty(s), freeze, seal → 속성 정의/제어
  • is, toString.call → 비교/타입 확인
  • get/setPrototypeOf, isExtensible, preventExtensions → 프로토타입/확장성 관리
반응형