자바스크립트/모던 자바스크립트

모던 자바스크립트, Reflect (리플렉트) 객체란?

Jake Seo 2023. 3. 20. 01:49

리플렉트 (Reflect) 란?

  • 자바스크립트의 built-in object 이다.
  • 일반적으로 프록시 객체의 핸들러에서 기본 동작을 제공하기 위해서 사용된다.
  • Object 가 가지는 메서드들을 비슷하게 가진다.
    • defineProperty()
    • getOwnPropertyDescriptor()
    • getPrototypeOf()
    • setPrototypeOf()
    • preventExtensions()
  • 생성자로 생성할 수 없는 객체이다. (it's not constructible)
    • Reflect.xxx() 와 같은 정적 메서드를 이용하기 위한 객체이다.
    • new Reflect() 는 아무런 의미가 없다.
  • 가로챌 수 있는 (interceptable) 자바스크립트 연산에 대한 메서드를 제공한다.
    • interceptable 의 의미는 프록시를 이용해 커스터마이징할 수 있는 연산을 말한다.
    • 모든 JS 연산이 interceptable 은 아니다.
      • delete 연산이나 . 으로 속성을 접근하는 등의 연산은 interceptable 하지 않다.

get 메서드 관련 특징: 형변환을 하지 않는다.

  • Object: getPrototypeOf() 를 수행하면 primitive 타입을 오브젝트로 변환한다.
  • Reflect: getPrototypeOf() 를 수행해도 primitive 타입을 오브젝트로 변환하지 않는다.
console.log(Object.getPrototypeOf(1));
/*
객체로 변환하여 처리
Number {0, constructor: ƒ, toExponential: ƒ, toFixed: ƒ, toPrecision: ƒ, …}
*/

console.log(Reflect.getPrototypeOf(1));
/*
객체로 변환하지 않고 에러를 던짐
Uncaught TypeError: Reflect.getPrototypeOf called on non-object
    at Reflect.getPrototypeOf (<anonymous>)
    at <anonymous>:1:9
*/

set 메서드 관련 특징: 결과로 객체를 반환하지 않는다.

  • Object.defineProperty() 를 수행하면, 객체의 내용을 반환한다.
  • Reflect.defineProperty() 를 수행하면, 성공/실패를 의미하는 true/false 를 반환한다.
const arr = [1, 2, 3];
arr.x = "123";
console.log(
  Object.defineProperty(arr, "x", {
    value: 10,
  })
);

/*
(3) [1, 2, 3, x: 10]
*/

console.log(
  Reflect.defineProperty(arr, "x", {
    value: 50,
  })
);

/*
true
*/

Reflect.apply()

function example(a, b, c) {
  console.log(`this.name = ${this.name}, a = ${a}, b = ${b}, c = ${c}`);
}

const thisArg = { name: "test" };
const args = [1, 2, 3];

Reflect.apply(example, thisArg, args);
example.apply(thisArg, args);
  • 위 소스코드에서 Reflect.apply()example.apply() 는 같은 역할을 한다.
  • Reflect.apply() 의 장점은 Function.prototype.apply() 가 변조되어도 사용 가능하다는 것이다.
    • JS 함수가 아니더라도, [[Call]] 내부 작업이 있는 모든 객체에서 작동한다.

Reflect.construct()

  • 생성자 함수를 통해 새 인스턴스를 만든다.
  • 기존 생성자와 2가지가 다르다.
    • 생성자에 대한 인수를 배열 혹은 배열과 유사한 객체로 받아들인다.
    • new.target 을 호출하는 함수 외에 다른 것으로 설정할 수 있다.
  • new 키워드 없이 Error, Array 같은 내장 객체의 하위 객체를 만드는데 유용하다.

과거의 생성자와 Reflect.construct()

  • ES5
function Person(name, age, gender) {
  this.name = name;
  this.age = age;
  this.gender = gender;

  this.sayHello = function () {
    console.log("Hello, my name is " + this.name);
  };

  return this;
}

var args = ["Alice", 25, "female"];
var person1 = Person.apply(Object.create(Person.prototype), args);

person1.sayHello(); // Output: "Hello, my name is Alice"
person1 instanceof Person;
  • ES 2015+
const person1 = new Person(...arguments);
  • Reflect.construct()
const person3 = Reflect.construct(Person, args);

커스텀 Error 함수 정의 예제

function buildCustomError(...args) {
  return Reflect.construct(Error, args, buildCustomError);
}

buildCustomError.prototype = Object.assign(Object.create(Error.prototype), {
  constructor: buildCustomError,
  report() {
    console.log(`this.message = ${this.message}`);
  },
});

const e = buildCustomError("커스텀 에러 메세지");
console.log("instanceof Error", e instanceof Error);
e.report();
console.log(e);
  • Error 의 생성자를 이용하기 때문에 this.message 를 할당하는 부분이 없어도 잘 동작한다.

Reflect.ownKeys()

  • Object.keys() 와 거의 유사하다.
  • 열거할 수 없는 키와 문자, 심볼로 이름이 지정된 키를 포함하여 키의 배열을 반환한다.
const obj = {
  name: "Alice",
  age: 25,
  [Symbol("id")]: 1234,
};

Object.defineProperty(obj, "secret", {
  value: 123123,
});

const reflectKeys = Reflect.ownKeys(obj);
const objectKeys = Object.keys(obj);

console.log(reflectKeys); // ['name', 'age', 'secret', Symbol(id)]
console.log(objectKeys); // ['name', 'age']

Reflect.get()

  • 객체의 속성을 가져온다.
  • Reflect.get(target, propertyName[, receiver])
    • descriptor 를 가져오고, 값을 반환한다.
    • 접근자면 접근자 함수를 수행한다.

super 를 사용하지 않고 부모 클래스의 메서드 가져오기

class Product {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }

  get result() {
    return this.x * this.y;
  }
}

class DoubleProduct extends Product {
  get result() {
    return super.result * 2;
  }
}

const d = new DoubleProduct(10, 2);
console.log(d.result);
  • super 를 빼고 구현해보자.

Reflect.get() 없이 구현하기

class DoubleProduct extends Product {
  get result() {
    const proto = Object.getPrototypeOf(Object.getPrototypeOf(this));
    const descriptor = Object.getOwnPropertyDescriptor(proto, "result");
    const superResult = descriptor.get.call(this);
    return superResult * 2;
  }
}
  • 프로토타입을 가져오는 절차를 거친 뒤 descriptor 를 가져와 get.call() 을 호출했다.

Reflect.get() 이용하기

class DoubleProduct extends Product {
  get result() {
    const proto = Object.getPrototypeOf(Object.getPrototypeOf(this));
    return Reflect.get(proto, "result", this) * 2;
  }
}
  • descriptor 를 가져오는 절차를 생략하고 한방에 가져왔다.

Reflect.set()

  • 프로퍼티의 값을 설정한다.
const object1 = {};
Reflect.set(object1, "property1", 42);

console.log(object1.property1); // 42

const array1 = ["duck", "duck", "duck"];
Reflect.set(array1, 2, "goose");

console.log(array1[2]); // goose
반응형