Search code examples
javascriptobjectjavascript-objects

Is it possible to redefine the base object valueOf to return an inner prop's value?


Question:

Is it possible to redefine the base object valueOf to return a inner prop?

let obj = {
  x: 1,
  y: 2
}

obj     // 2 <- the value of obj.y
obj.x   // 1
obj.y   // 2

Solution

  • Of course it's possible to define a valueOf method that returns a member, but you still need to call the method somehow - either implicitly in a conversion, or explicitly. valueOf doesn't magically make obj itself become a different thing.

    const obj = {
      x: 1,
      y: 2,
      valueOf() {
        return this.y;
      }
    };
    
    console.log(obj);
    console.log(obj.x, obj.y)
    console.log(obj.valueOf())
    console.log(obj + 5)
    console.log("y: " + obj)