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 @   DL·Coder  阅读(62)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示