weijiyang / GOOD-IDEA

这里记录一些灵感~详见ISSUES
1 stars 0 forks source link

== 隐式转换 #58

Open weijiyang opened 4 years ago

weijiyang commented 4 years ago

利用toString

let a = {
  i: 1,
  toString () {
    return a.i++
  }
}

if(a == 1 && a == 2 && a == 3) {
  console.log('1');
}

利用valueOf


let a = {
i: 1,
valueOf () {
return a.i++
}
}

if(a == 1 && a == 2 && a == 3) { console.log('1'); }

> 数组这个就有点妖了

var a = [1,2,3]; a.join = a.shift; if(a == 1 && a == 2 && a == 3) { console.log('1'); }

> ES6的symbol

let a = {[Symbol.toPrimitive]: ((i) => () => ++i) (0)}; if(a == 1 && a == 2 && a == 3) { console.log('1'); }