0

I am trying to override valueOf and toString

This is becouse I want to add some properties to the premitive values

So I created this below

class Box {
  #value;
  constructor(value) {
    this.#value = value;
  } 
  
  valueOf() {
    return this.#value;
  }
  
  toString(){
    return this.#value;
  }
  
  someMethod(){
    return "something else"
  }
}

const t1 =21;
const t2 = 21
const p = new  Box(45);
const s = new  Box(45);
console.log(p === s, t1 === t2)

notice that t1 and t2 comparesion works great but p and s are not working as expected

Why is that and is there a way to do the thing I want?

Alen.Toma
  • 4,684
  • 2
  • 14
  • 31
  • 2
    `p === s` doesn't do any coercing when comparing objects so your overrides have no bearing, it checks if the two operands reference the same object. – pilchard Dec 08 '22 at 09:02
  • Yes I know that but what I want is to create my own type and make it work the same way as t1 and t2 so the developers do not notice a change when using the library and Only the library uses `someMethod` – Alen.Toma Dec 08 '22 at 09:05
  • You can't make an object operate the same way as a primitive. If you force js to coerce your class objects then you'll see it is 'working' `+p === +s // true` – pilchard Dec 08 '22 at 09:06
  • Is there other way, I mean react uses it when using `usestate` – Alen.Toma Dec 08 '22 at 09:06
  • `useState` just relies on referential comparison, which is why you can't mutate an object and expect a change. `a = {a:1}; b = a; a === b; //true`. (specifically [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is)) – pilchard Dec 08 '22 at 09:07

0 Answers0