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

后端 未结 2 646
耶瑟儿~
耶瑟儿~ 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.

    0 讨论(0)
  • 2021-01-08 01:21

    Basically, that's because Internet Explorer's window object exposes an item() method that your script cannot overwrite.

    In the line:

    item = new Object();
    

    item is not declared in the local scope, so it is interpreted as a property of the global object (window.item). On Firefox, window does not expose a member named item, so a new member is introduced and the result of new Object() is assigned to it.

    On the other hand, Internet Explorer exposes a native method named window.item(). That member is not writeable, so the assignment cannot take place -- it is silently ignored. In other words, item = new Object() has no effect at all (well, it does create an object but cannot assign it afterwards).

    The subsequent assignments to id and name end up creating new members of the item() method. These are always the same members of the same method, so their values are overwritten on every loop iteration. In addition, the same object (the item() method) is pushed to the array on every iteration.

    Therefore, the array ends up containing three times the same object, and the values of its id and name members are the last values assigned to them (in the last iteration), respectively 3 and 'c'.

    0 讨论(0)
提交回复
热议问题