wtfjs
wtfjs copied to clipboard
[Example] const is equal to multiple numbers
Example
const a = new Proxy({ i: 1 }, {
get: (target) => () => target.i++,
})
console.log(a == 1, a == 2, a == 3);
Explaination
- Every time when comparing, property
[Symbol.toPrimitive]
is accessed - Proxy returns a function, that is called
- 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++;
}
}