ES6 Reflect API

Denz
6 min readNov 29, 2015

--

Firefox 43에서 대부분 잘 동작함.
Firefox DeveloperEdition ( ver 45 )에서 더 잘 동작함.

Reflect API
- ES6에서 새롭게 추가된 API.
- 객체의 속성과 메서드를 조사하고 조작하는 API.
- 기존의 ES5에도 이를 위한 API 가 존재했지만 이를 잘 정리해 놓은 것.
- 읽고 쓰기 쉬움.
- 실패시 exception을 던지지 않음. 대신 결과에 대한 boolean 값을 반환함.
- ECMAScript 2015에 14개의 메서드를 정의함.

Reflect 는 함수가 아님.
Reflect() : X
new Reflect() : X
Math 와 같은 개념.

  1. Reflect.apply(function, this, args) Function.prototype.apply()
    기존에 Function의 apply()와 같음.
    .apply 보다 코드가 더 명확하여 좀 더 읽기 쉬움?

2. Reflect.construct(constructor, args, prototype) new operator
function를 new 한 것과 같음.
prototype를 명시적으로 지정해 줄 수 있음.

firefox 43은 prototype이 제대로 적용되지 않음.
firefox DeveloperEdition( version 44.0a2 )에서는 동작함.

3. Reflect.defineProperty(object, property, descriptor) — Object.defineProperty()
descriptor을 이용해 객체에 새로운 property를 추가거나 기존의 property를 수정함.

Object.defineProperty는 변경된 객체를 반환하고( 실패시 throw exception ) Reflect.defineProperty()는 적용 결과(Boolean)를 반환한다.

property descriptor에 대한 내용은 여기에…

console.dir(obj)

4. Reflect.deleteProperty(object, property) — delete operator
객체의 property 삭제.
delete operator와 같다.

5. Reflect.enumerate(object) — for … in
인자로 주어진 객체의 iterator를 반환한다.

구현된 브라우저 없음.

6. Reflect.get(object, property, this)
객체의 property 값을 반환한다.

7. Reflect.set(object, property, value, this)
객체에 property-value 값을 설정한다.

8. Reflect.getOwnPropertyDescriptor(object, property) — Object.getOwnPropertyDescriptor()
property의 descriptor를 반환한다.

9. Reflect.setPrototypeOf(object, prototype) — Object.setPrototypeOf()
객체의 prototype을 다른 객체나 null 로 변경한다.

10. Reflect.getPrototypeOf(object) — Object.getPrototypeOf()
객체의 prototype을 반환한다..

11. Reflect.has(object, property) — in operator
property의 소유 여부를 반환한다.
in 연산자와 동일하다.
상속받은 property의 경우도 true를 반환한다.

12. Reflect.isExtensible(object) — Object.isExtensible()
인자로 주어진 객체의 extensible 여부를 반환한다.

13. Reflect.preventExtensions(object) — Object.preventExtensions()
객체의 확장성을 제약한다.
새로운 property를 추가할 수 없다.

14. Reflect.ownKeys(object)
인자로 주어진 객체의 key 모음(배열)을 반환한다.
상속 받은 property는 반환하지 않는다.
Object.getOwnPropertyNames() 와는 Symbol key을 반환한다는 점에서 다르다.

Object.getOwnPropertyNames(target).concat(Object.getOwnPropertySymbols(target)) 와 Reflect.ownKeys(target) 이 같다.

Object.keys();
enumerable property 의 key만 반환한다.

Object.getOwnPropertyNames();
enumerable or not property의 key를 반환한다.

--

--