面试笔记:a==5&& a==8

176 阅读1分钟

问题引发

在面试时,面试官出了一道题a的值让条件 a==5&& a==8成立,有多少种解决方式

1.通过重写Obj的valueOf

const a = { value : 2 };
a.valueOf = function() { 
    return this.value += 3;
};
console.log(a==5 && a== 8)

2.通过重写Obj的toString

var a={
    i:1,
     valueOf:null,
    toString:()=>{
         return a.i++
    }
}

3.通过Obj.defineProperty

var a = 2
Object.defineProperty(window, 'a', {
    get() {
        return window.a += 3
    },
    set(val) {
        console.log(val)
    }
})

理论上是没问题但是结果报错了,报的是不能重新定义a

Uncaught TypeError: Cannot redefine property: a

排查结果,通过获取属性的描述getOwnPropertyDescriptor

var a = 1Object.getOwnPropertyDescriptor(window, "a");// {value: 1, writable: true, enumerable: true, configurable: false}

通过a挂在在window上的configurable是不可配置的。也就是不能重新定义的

那么问题来了,window是不可配置,array其他内置对象会这样么

Array.a = 1
Object.getOwnPropertyDescriptor(Array, "a");
// {value: 1, writable: true, enumerable: true, configurable: true}

String.a = 1
Object.getOwnPropertyDescriptor(String, "a");
// {value: 1, writable: true, enumerable: true, configurable: true}

重新定义新的变量

var val=2
Object.defineProperty(window,'a',{
    get:()=>{return val+=3}
})