자바스크립트/개념

Object.prototype.valueOf() 란?

Jake Seo 2023. 1. 1. 22:21

Object.prototype.valueOf() 란?

  • Object 에서는 기본 동작으로 thisObject 형태로 변환해 반환한다.
  • 기본 정의를 오버라이드하여 쓰는 경우가 많다.
  • 보통은 자바스크립트에서 오브젝트를 primitive value 로 변환하기 위해 사용하는 메서드이다.
  • 직접 호출하는 경우는 드물고 보통은 자동으로 호출된다.
const o = {};
const str = "test string";

console.log(Object.prototype.valueOf.call(o)); // {}
console.log(Object.prototype.valueOf.call(str)); // String {'test string'}
console.log(new Object(str)); // String {'test string'}
  • o 는 원래 오브젝트여서 그대로 반환된다.
  • strnew Object() 를 통해 형변환한 것과 똑같이 반환된다.

클래스에서의 용례

class Box {
  #value;
  constructor(value) {
    this.#value = value;
  }
  valueOf() {
    return this.#value;
  }
}

const parcelBox = new Box("Parcel Box");
console.log("" + parcelBox); // Parcel Box
  • 어떤 클래스를 단순히 값으로 표현하고 싶을 때, 오버라이드하면 유용하다.
  • 자동으로 변환된다.
  • 그러나 우선순위가 [Symbol.toPrimitive] 접근자 메서드에 밀린다.
class Box {
  #value;
  constructor(value) {
    this.#value = value;
  }
  valueOf() {
    return this.#value;
  }
  [Symbol.toPrimitive](hint) {
    return "toPrimitive";
  }
}

const parcelBox = new Box("Parcel Box");
console.log("" + parcelBox); // toPrimitive
반응형