Search code examples
javascriptarraysprototypejsmootools

MooTools and Array prototype


Mootools is overridding the Array prototype, and the problem is that this prototype and I have an external .js (a library that I can't modify manually) that iterates using for(i in someArray) and it is throwing exception, since now Array has more properties. Any ideas of how to overcome this problem ? I was thinking about removing those properties from array on the Mootools library itself, but it seems is not that easy.


Solution

  • First of all, you should use a regular for(var i=0; i < arr.length; i++) { var el = arr[i]; } loop on arrays.

    If you really need for..in and you are working in modern browsers, then you can modify the modification to the prototype to make it non-enumerable.

    //Logger function
    function logArray(arr) {
        console.log("--TEST-START--");
        for (var i in arr) {
          console.log(arr[i])
        }
        console.log("--TEST-END--");
      }
      //Modify prototype
    Array.prototype.a = {
      b: 0
    };
    //List to test against
    var list = [1, 2, 3, 4];
    //Log initial list
    logArray(list);
    //Modify prototype modificiation
    Object.defineProperty(Array.prototype, 'a', {
      enumerable: false
    });
    
    //Log initial list
    logArray(list);