I recently found a question on StackOverflow that looked something like this:
// Please fill in your answer in the question mark to make the equation below true
leta = ? ;if(a == 1 && a == 2 && a == 3) {
console.log("Hi, I'm Echi");
}
Copy the code
As soon as I saw this problem, I believe that most people have at least two kinds of implementation plans in their minds. We know that when an object is converted to a primitive type, it first calls valueOf and then toString, so we tried to override both methods.
(a) valueOf implementation
let a = {
i: 1,
valueOf() {
returna.i++; }};if(a == 1 && a == 2 && a == 3) {
console.log("Hi, I'm Echi");
}
Copy the code
(2) use toString implementation
let a = {
i: 1,
toString() {
returna.i++; }};if(a == 1 && a == 2 && a == 3) {
console.log("Hi, I'm Echi");
}
Copy the code
Next we look at the object’s symbol.toprimitive property, which points to a method. This method is called when an object is converted to a value of the original type, returns the value of the original type of the object, and has the highest priority when converted to a primitive type. So we have a third option:
(3) Use Symbol. ToPrimitive implementation
let a = {
i: 1[Symbol.toPrimitive]() {
returna.i++; }};if(a == 1 && a == 2 && a == 3) {
console.log("Hi, I'm Echi");
}
Copy the code
Ok, so that’s my solution to this problem, mostly using the implicit conversion of == to variable types, but you might have other solutions. For example, you can use ES5’s Object.defineProperty or ES6’s Proxy, which I won’t write here;
And the last thing I want to ask you is, if I replace === == with === =, is it still the same? Why? Please leave comments and discuss
For more details, check out StackOverflow yourself;
Link to this article: juejin.cn/user/729731… Copyright Notice: This article is licensed BY @BY-NC-SA unless otherwise stated. Reprint please indicate the source!