Proxy 처럼 자바스크립트의 명령을 가로챌 수 있는 메서드를 제공하는 내장 객체입니다.
Reflect 는 함수가 아닌 일반 객체이다!!
기본 객체 내장 메서드명을 객체 속성명으로 사용할 경우 버그를 방어하기위해 오류를 냅니다. Object.prototype
의 메서드를 인스턴스에서 사용하지 못하게 하는데 그래서 obj.hasOwnProperty
를 사용하지 못하고 Object.prototype.hasOwnProperty.call
로 길게 사용해야했습니다. Reflect
를 사용하면 간편하게 해결됩니다.
const obj = { prop: 1, hasOwnProperty: 2 };
// obj 객체에 prop 속성이 있는지 확인
obj.hasOwnProperty('prop') //TypeError: obj.hasOwnProperty is not a function
console.log(obj.hasOwnProperty); // 2
console.log(Object.prototype.hasOwnProperty.call(obj, 'prop')); // true
// Reflect
Reflect.hasOwnProperty(obj, 'prop'); // true
Reflect.get(target, property [,receiver])
Reflect.get
메서드는 기본적으로 target[propertyKey]
를 반환합니다. target
이 객체가 아닐 경우 TypeError
를 발생시킨다. 일반 객체 참조와 다른점은 undefined
반환보다 더 명확한 에러를 나타내준다는 점이있다.
const obj = { name: 'bigOne' };
console.log(Reflect.get(obj, 'name')); // bigOne
const str = '';
console.log(Refelct.get(str, 'name')); // TypeError: Reflect.get called on non-object
console.log(str['name']); // undefined
Reflect.set(target, property, V [, receiver])
Reflect.get
과 흡사하게 동작하지만 객체에 할당할 V (value 값)
라는 인자가 추가된다.
const obj = { name: 'bigOne' };
Reflect.set(obj, 'age', 28);
console.log(obj); // { name: 'bigOne', age: 28 }
const str = '';
Reflect.set(str, 'age', 28); // TypeError: Reflect.set called on non-object
str['age'] = 28; // 아무런 것도 반환되지 않음 즉, Error 발생되지 않음
Reflect.get, Reflect.set
의 receiver
는 target[propertyKey]
가 getter, setter
일 때 this
의 컨텍스트로 동작하게 됩니다. 즉, receiver
를 통해 this 바인딩을
조절할 수 있다는 의미입니다.
const obj = {
a: 1,
b: 2,
get sum() {
return this.a + this.b;
}
};
const receiverObj = {
a: 5,
b: 3,
};
Reflect(obj, 'sum', obj); // 3
Reflect(obj, 'sum', receiverObj); // 8 -> this를 receiverObj 객체가 되므로 5 + 3