Implicitly global “item” variable - difference between Internet Explorer and FireFox

后端 未结 2 647
耶瑟儿~
耶瑟儿~ 2021-01-08 00:49

Just out of curiosity..

I have this JS code:

var someExternalArray = [{id: 1, name: \'a\'}, {id: 2, name: \'b\'}, {id: 3, name: \'c\'}];
var newArray         


        
2条回答
  •  再見小時候
    2021-01-08 01:18

    This is tricky. For some obscure reason, Internet Explorer has a native method called item in the global context window (if someone knows why, you're welcome to share: I can't find it in the documentation). So, when you use the identifier item without declaring a variable, it refers to this method.

    The first instruction in the loop (item = new Object();) does nothing because window.item is a readonly property. So, after this instruction, window.item is still the native function.

    The next instructions (those which sets id and name) works, because while the property window.item is readonly, the Function object it's pointing to can be modified.

    After the loops, you added the same Function object three times, and only the last iteration counts because you override the id and name properties everytime.

提交回复
热议问题