Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

实现 a == 1 && a == 2 && a == 3 #25

Open
nmsn opened this issue Nov 29, 2022 · 3 comments
Open

实现 a == 1 && a == 2 && a == 3 #25

nmsn opened this issue Nov 29, 2022 · 3 comments

Comments

@nmsn
Copy link
Contributor

nmsn commented Nov 29, 2022

如题

https://mp.weixin.qq.com/s/OBb0zrfGAI6w4ILvT5T5-A

@nmsn
Copy link
Contributor Author

nmsn commented Nov 29, 2022

方法一: 利用隐式转换会调用 valueOf

const a = {
  value: 1,
  valueOf() {
    return this.value++
  }
};

console.log(a == 1 && a == 2 && a == 3) // true

@nmsn
Copy link
Contributor Author

nmsn commented Nov 29, 2022

方案二: 在对象 valueOf 函数不存在的情况下会调用 toString 方法

const a = {
  value: 1,
  toString() {
    return this.value++;
  }
};

console.log(a == 1 && a == 2 && a == 3) // true

@nmsn
Copy link
Contributor Author

nmsn commented Nov 29, 2022

方案三: 利用 Object.defineProperty 在全局 window 上挂载一个 a 属性

let _a = 1
Object.defineProperty(window, 'a', {
  get() {
    return _a++
  }
});

console.log(a == 1 && a == 2 && a == 3)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant