wtfjs icon indicating copy to clipboard operation
wtfjs copied to clipboard

[Example] const is equal to multiple numbers

Open AlexXanderGrib opened this issue 2 years ago • 0 comments

Example

const a = new Proxy({ i: 1 }, { 
  get: (target) => () => target.i++,
})

console.log(a == 1, a == 2, a == 3);

Explaination

  1. Every time when comparing, property [Symbol.toPrimitive] is accessed
  2. Proxy returns a function, that is called
  3. So value is compared with result of the function
const a = new Proxy({ i: 1 }, {
  get(target, property) {
    console.trace("[Proxy] get() called with", { target, property });

    return function inner() {
      console.trace("[Proxy] inner() called");

      return target.i++;
    }
  }
})

console.log(a == 1, a == 2, a == 3);

Log

[Proxy] get() called with
{
  target: { i: 1 },
  property: Symbol(Symbol.toPrimitve)
}
[Proxy] inner() called
...

Basically, object is equal to

const a = {
  i: 1,
  [Symbol.toPrimitive]() {
    return this.i++;
  }
}

AlexXanderGrib avatar Oct 10 '22 11:10 AlexXanderGrib