a === 1 && a === 2 && a===3

Object.defineProperty 实现

  • 相当于全局劫持 a ,只要发现 a ,就执行方法(三目运算符);
Object.defineProperty(window, 'a', {
  get: function () {
    //this指向window.a
    this.value ? this.value++ : this.value = 1;
    return this.value;
  }
})
console.log(a) // 1
console.log(a) // 2
console.log(a) // 3
if (a === 1 && a === 2 && a === 3) {
  console.log("OK")
}

a == 1 && a == 2 && a==3

  • “宽松相等操作符(==)” 使用的时候,会先进行类型的转换,调用 valueOf() 方法或者 toString() 方法;

  • valueOf() 方法优先级大于 toString() 方法,调用了valueOf(),就不会调用 toString() 方法;

var a = {
  n: 0,

  //私有属性方法
  valueOf: function () {
    return ++this.n
  },

  toString: function () {
    return ++this.n
  }
}
//此时的a.toString()调用的不再是Object.prototype.toString(),而是自己私有的属性方法toString();
if (a == 1 && a == 2 && a == 3) {
  console.log("OK")
}
posted @ 2022-09-01 14:11  DL·Coder  阅读(43)  评论(0编辑  收藏  举报