This is a short article about JavaScript features. I plan to write articles on these small knowledge points whenever I have time.
In JavaScript, define a variable a
such that:
a == 1 && a == 2 && a == 3 === true
Solution 1: Rewrite the valueOf
method#
- Code Example:
let value = 0;
const a = {
valueOf: function() {
return ++value;
}
};
console.assert(a==1 && a==2 && a==3, true);
-
Principle:
- When
a
is used in comparison operations (e.g.,a == 1
), the JavaScript engine callsa.valueOf()
to get its primitive value. - We rewrite the
valueOf
method to return an incremented value each time it is called.
- When
-
Result:
- First comparison:
a.valueOf()
returns1
, soa == 1
. - Second comparison:
a.valueOf()
returns2
, soa == 2
. - Third comparison:
a.valueOf()
returns3
, soa == 3
.
- First comparison:
Solution 2: Use a Proxy
object#
- Code Example:
let value = 0;
const a = new Proxy({}, {
get: function(target, name) {
return ++value;
}
});
console.assert(a.anyProperty == 1 && a.anyProperty == 2 && a.anyProperty == 3, true);
-
Principle:
- The
Proxy
object is used to create a proxy for an object, allowing us to intercept and customize fundamental operations, such as property access. - We intercept any property access on
a
and return an incremented value each time it is accessed.
- The
-
Result:
- Similar to the
valueOf
method, each property access returns an incremented value.
- Similar to the