Search code examples
javascriptmootoolsprototype-programming

Javascript prototype for...in Iterators?


Due to the problem I posted here Mootools when using For(...in Array) problem about some javascript framework will prototype the Array object, and some other's codes(a forum engine) did use For...in Loop to loop Arrays, when I plug the javascript framework into these existing codes, things will go wrong.

//BEFORE
for(key in [1,2,3,4]) console.log(key)    //0,1,2,3 keys of the array

//After JS Framework
for(key in [1,2,3,4]) console.log(key)    //0,1,2,3,$family,$constructor,pop,push,reverse,shift,sort,splice

Given that I cannot touch the original codes which contains these For..In Array loops, and I also want to use the javascript framework (mootools)

Can I work around this by e.g. prototype the javascript Iterator??

somehow to overload the For...In loop, to make all my javascript For...in loop to scan for array type and only return the value but not the function? I donno how to do this but i wonder if this can be done?


Solution

  • The original code is broken... that is really a shame.

    With Mozilla JavaScript -- don't confuse the Mozilla JavaScript extensions with ECMAScript -- it is possible to define a custom Iterator for the object. See What's new in JavaScript 1.7. However, this is likely not practical in this scenario.

    My suggestions are thus:

    1. Fix the code
      • It should use hasOwnProperty for key iteration, or;
      • i < arr.length for array index iteration.
    2. Keep mootools from messing with prototypes of built-in objects.
      • Refer to the mootools documentation (I don't use mootools).
    3. Use a framework that doesn't mess with the prototypes of built-in objects.
      • jQuery doesn't mess with prototypes.

    Happy coding.