美文网首页
a===1 && a===2 && a===3

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

作者: WHU_GIS_LJ | 来源:发表于2018-08-26 10:44 被阅读0次

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

    • 利用松散相等运算符 == 的原理,自定义toString或者valueOf返回值
    let a = {
      value: 0,
      toString() {
        return  ++ a.value
      }
    }
    console.log(a == 1) //true
    console.log(a == 2) //true
    console.log(a == 3) //true
    

    2. obj.a===1 && obj.a===2 && obj.a===3

    2.1 劫持js对象的getter

    • 若obj对象为window对象,则可实现 a===1 && a===2 && a===3
    let obj = {
      value: 1
    }
    Object.defineProperty(obj,'a', {
      get() {
        return this.value ++
      }
    })
    console.log(obj.a === 1) // true
    console.log(obj.a === 2) // true
    console.log(obj.a === 3) // true
    
    2.2利用es6的代理proxy
    let obj = {
      value: 1
    }
    let proxy = new Proxy(obj, {
      get(target, key, receiver) {
        if(key === 'a') {
          return target.value ++
        } 
      }
    })
    console.log(obj.a === 1) // true
    console.log(obj.a === 2) // true
    console.log(obj.a === 3) // true
    

    相关文章

      网友评论

          本文标题:a===1 && a===2 && a===3

          本文链接:https://www.haomeiwen.com/subject/hvzniftx.html