mortal-cultivation-biography / daydayup

A FE interview-questions collection repo.
8 stars 0 forks source link

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

Open nmsn opened 1 year ago

nmsn commented 1 year ago

如题

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

nmsn commented 1 year ago

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

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

console.log(a == 1 && a == 2 && a == 3) // true
nmsn commented 1 year ago

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

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

console.log(a == 1 && a == 2 && a == 3) // true
nmsn commented 1 year ago

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

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

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