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
ais used in comparison operations (e.g.,a == 1), the JavaScript engine callsa.valueOf()to get its primitive value. - We rewrite the
valueOfmethod 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
Proxyobject 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
aand return an incremented value each time it is accessed.
- The
-
Result:
- Similar to the
valueOfmethod, each property access returns an incremented value.
- Similar to the