Safely extending Array.prototype


  • TMB

    I had started writting a module that for now, adds a couple methods to the Array.prototype.
    Nothing yet in my running code was using this module, this module wouldn't interact with anything, and yet the simple fact of requiring this module made all sorts of things go wrong.

    Turns out, every function I added to the Array prototype was then considered a part of every array's content; for (let i in []); would actually run a cycle for each function I had wrote.

    But then, how is it possible for Arrays to have native functions that aren't included in their content? Is it possible to add my own there ?



  • You can use Object.defineProperty with {enumerable: false}.

    > Array.prototype.foo = function() {return 'bar';}
    > for (let i in ['a', 'b', 'c']) console.log(i);
    0
    1
    2
    foo
    > Object.defineProperty(Array.prototype, 'foo', {value: function() {return 'bar';}, enumerable: false})
    > for (let i in ['a', 'b', 'c']) console.log(i);
    0
    1
    2