[JS]객체 생성방식에 따른 추상연산

현우.·2024년 11월 8일
post-thumbnail

객체 생성방식에 따른 추상연산 과정

ordinaryObjectCreate는 객체를 생성할 때 자주 사용되는 중요한 추상 연산입니다.

특히, JavaScript에서 객체를 생성할 때 기본적으로 호출되는 연산으로, Object 생성자 함수객체 리터럴 방식에서 객체를 생성할 때 사용된다.

이 연산은 빈 객체를 생성할 때 호출되며, 객체의 [[Prototype]]을 설정하고, 객체의 내부 속성들을 초기화하는 작업을 담당한다.

OrdinaryObjectCreate 동작과정

  1. 새 객체 생성
    먼저 빈객체를 생성합니다.

  2. [[Prototype]] 설정
    새로 생성된 객체의 [[Prototype]]을 지정된 객체로 설정합니다.
    이때 기본적으로 [[Prototype]]Object.prototype이 됩니다.

  3. 객체 속성 초기화
    객체의 기본 내부 속성([[Prototype]] 외에도 [[Extensible]] 등)을 초기화합니다.
    이후, 객체 리터럴에서 정의된 속성들이 추가됩니다.

OrdinaryObjectCreate의 사용 예시

// 객체 리터럴 사용 시 내부적으로 호출되는 방식
const obj = { key: 'value' };
// 엔진의 내부 과정:
const obj = OrdinaryObjectCreate(Object.prototype); // 빈 객체 생성 및 [[Prototype]] 설정
// key: 'value' 속성 추가

console.log(obj); // { key: 'value' }

OrdinaryObjectCreate와 다른 객체 생성 방식의 비교

  1. 객체 리터럴
const obj = { key: 'value' };
  • OrdinaryObjectCreate(Object.prototype) 호출.
  • key: 'value' 속성 정의.
  1. new Object()
const obj = new Object();
  • OrdinaryObjectCreate(Object.prototype) 호출.
  • 빈 객체가 반환됩니다.
  1. Object.create()
const obj = Object.create(null);
  • Object.create(proto)는 지정된 proto[[Prototype]]으로 사용하는 객체를 만듭니다.
  • 이 경우 OrdinaryObjectCreate(proto)가 호출되며, protonull이라면 프로토타입이 없는 객체가 생성됩니다.
  1. 생성자 함수(클래스)
function Person(name) {
    this.name = name;
}

const person = new Person('Alice');
console.log(person); // Person { name: 'Alice' }
  • OrdinaryObjectCreate(Person.prototype)가 호출되어 새 객체를 생성
  • Person.prototype[[Prototype]]으로 설정됩니다.
  • 생성자 함수 내부에서 this.name = name처럼 객체의 프로퍼티가 추가됩니다.
  • person 객체가 반환됩니다.

ordinaryObjectCreate가 호출되지 않는 경우

1. Object.create(proto)에서 protonull일 때

Object.create(proto) 메서드는 proto를 지정하여 새로운 객체를 생성하는데, 이때 protonull인 경우에는 객체의 [[Prototype]]null로 설정됩니다.

이때 OrdinaryObjectCreate는 여전히 호출되지만, 새로운 객체의 프로토타입이 null로 설정되기 때문에, [[Prototype]]이 비어 있는 객체가 생성됩니다.

   const obj = Object.create(null);  // [[Prototype]]이 null인 객체 생성
   console.log(obj);  // {}
   console.log(Object.getPrototypeOf(obj));  // null

2. new Object(value)에서 value가 객체일 때

new Object(value)에서 value가 객체라면, OrdinaryObjectCreate가 호출되지 않습니다. 이 경우 value가 이미 객체이므로, 그 객체가 그대로 반환되기 때문입니다.

const obj1 = { key: 'value' };
const obj2 = new Object(obj1);  // obj1이 이미 객체이므로 그대로 반환됨

console.log(obj1 === obj2);  // true
profile
학습 기록.

0개의 댓글