Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Modifying the built-in object prototypes can be a bad idea in general, because it always has the potential to clash with other code on the same page.</p> <p>In the case of the Array object prototype, it is an especially bad idea, because it has the potential to interfere with any piece of code that iterates over the members of any array, for instance with <code>for .. in</code>.</p> <p>To illustrate using an example (borrowed from <a href="https://stackoverflow.com/questions/500504/javascript-for-in-with-arrays/500531#500531">here</a>):</p> <pre><code>Array.prototype.foo = 1; // somewhere deep in other javascript code... var a = [1,2,3,4,5]; for (x in a){ // Now foo is a part of EVERY array and // will show up here as a value of 'x' } </code></pre> <p>It would be better for you to create your own type of object constructor complete with doSomething function, rather than extending the built-in Array.</p> <hr> <p>Edit: to repeat what I put in a comment:</p> <blockquote> <p>The inverse is true - you should avoid for..in in case some n00b has modified the Array prototype, and you should avoid modifying the Array prototype in case some n00b has used for..in on an array. ;)</p> </blockquote> <p>Also, there now exists <code>Object.defineProperty</code> as a general way of extending object prototypes without the new properties being enumerable, though I still wouldn't use this as justification for extending the <em>built-in</em> types, because even besides <code>for..in</code> there is still the potential for other conflicts with other scripts. Consider someone forking your code and then putting both versions on the same page - will your custom enhancement to the Array object still work as you expect?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload