let num = 1
Object.defineProperty(window,‘a‘,{
get(){
return num++
},
set(){
}
})
console.log(a==1&&a==2&&a==3) // => true
如果是 == 两个等号,js会进行隐式转换
js在进行隐式转换的过程中,会调用toString和ValueOf方法(方法是对象原型链上的),向数字和字符串转化,所以,我们可以通过这两个方法,做一些手脚
let a = {
num:1,
toString(){
return this.num++
}
}
console.log(a==1&&a==2&&a==3) // => true
let a = {
num:1,
valueOf(){
return this.num++
}
}
console.log(a==1&&a==2&&a==3) // => true
原文:https://www.cnblogs.com/zoo-x/p/14845482.html