JavaScript Reflect

agnusdei·2023년 7월 18일
0

Reflect 객체는 ECMAScript 6(ES6)에서 추가된 내장 객체로서, JavaScript의 리플렉션(Reflection) 기능을 제공합니다. 리플렉션은 코드를 실행하는 동안 객체의 구조를 조사하고 수정하는 능력을 가리킵니다. Reflect 객체는 여러 유틸리티 메서드를 제공하여 객체의 속성, 프로퍼티, 메서드를 다루거나 프락시(Proxy)를 사용하는 데 도움이 됩니다.

Reflect 객체의 주요 메서드는 다음과 같습니다:

  1. Reflect.apply(target, thisArgument, argumentsList): 지정한 함수(target)를 주어진 this 컨텍스트(thisArgument)로 호출하며, 인수들(argumentsList)을 전달합니다.

  2. Reflect.construct(target, argumentsList[, newTarget]): 지정한 생성자(target)를 주어진 인수들(argumentsList)로 호출하여 새로운 인스턴스를 생성합니다. newTarget 인수를 제공하면, target 생성자 대신 해당 생성자를 호출합니다.

  3. Reflect.get(target, propertyKey[, receiver]): 지정한 객체(target)의 속성(propertyKey) 값을 가져옵니다. receiver를 제공하면 해당 객체의 속성 값을 호출하는 형태에 맞게 반환합니다.

  4. Reflect.set(target, propertyKey, value[, receiver]): 지정한 객체(target)의 속성(propertyKey) 값을 주어진 값(value)으로 설정합니다. receiver를 제공하면 해당 객체의 속성을 설정하는 형태에 맞게 처리합니다.

  5. Reflect.has(target, propertyKey): 지정한 객체(target)에 주어진 속성(propertyKey)이 존재하는지 여부를 확인합니다. 속성이 존재하면 true, 그렇지 않으면 false를 반환합니다.

  6. Reflect.deleteProperty(target, propertyKey): 지정한 객체(target)에서 주어진 속성(propertyKey)을 제거합니다.

  7. Reflect.getOwnPropertyDescriptor(target, propertyKey): 지정한 객체(target)의 주어진 속성(propertyKey)에 대한 속성 서술자를 반환합니다.

  8. Reflect.getPrototypeOf(target): 지정한 객체(target)의 프로토타입을 반환합니다.

  9. Reflect.setPrototypeOf(target, prototype): 지정한 객체(target)의 프로토타입을 주어진 객체(prototype)로 설정합니다.

  10. Reflect.preventExtensions(target): 지정한 객체(target)를 확장할 수 없도록 설정합니다.

  11. Reflect.isExtensible(target): 지정한 객체(target)가 확장 가능한지 여부를 확인합니다.

Reflect 객체의 메서드는 try...catch 블록과 함께 사용하면 더욱 유용하며, 객체의 조작과 예외 처리를 더욱 효율적으로 수행할 수 있게 합니다. 또한 Proxy 객체와 함께 사용하여 프로퍼티를 가로채거나 변경할 때 편리하게 활용할 수 있습니다.

const obj = {
  name: 'John',
  age: 30,
};

// Reflect.get 메서드로 속성 값을 가져옵니다.
const nameValue = Reflect.get(obj, 'name');
console.log(nameValue); // 출력: "John"

// Reflect.set 메서드로 속성 값을 변경합니다.
Reflect.set(obj, 'age', 35);
console.log(obj.age); // 출력: 35

// Reflect.has 메서드로 속성의 존재 여부를 확인합니다.
const hasName = Reflect.has(obj, 'name');
console.log(hasName); // 출력: true

// Reflect.deleteProperty 메서드로 속성을 제거합니다.
Reflect.deleteProperty(obj, 'age');
console.log(obj); // 출력: { name: 'John' }

위 예제에서는 Reflect 객체의 몇 가지 메서드를 사용하여 객체의 속성 값을 가져오고 변경하며, 속성의 존재 여부를 확인하고 제거하는 방법을 보여줍니다.

1개의 댓글

comment-user-thumbnail
2023년 7월 18일

글이 잘 정리되어 있네요. 감사합니다.

답글 달기