Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>It is considered by most a bad practice to extend native objects like <code>Array</code>. That is what the post you mentioned was getting at. The concern is you do not know how this will effect the behavior of other scripts.</p> <p>Here is an example of a scenario where poorly written caused issues once the array prototype was manipulated. This is a scenario I ran into once on a large code based which was really hard to track down:</p> <pre><code>function BadUseOfForLoop(){ //You should NEVER use a for in loop to iterate over an array //although some people do this and it works until you extend Array var arr = [1,2,3,4]; for (key in arr){ console.log(arr[key]); } } BadUseOfForLoop(); console.log("Extend Array..."); Array.prototype.sortBy = function(){ return "Doesnt matter..."; }; BadUseOfForLoop(); </code></pre> <p>Output:</p> <pre><code>1 2 3 4 Extend Array... 1 2 3 4 function (){ return "Doesnt matter..."; } </code></pre> <p><a href="http://jsfiddle.net/vTwRY/" rel="nofollow">http://jsfiddle.net/vTwRY/</a></p> <p>One thing you could do to avoid the caveat is simply not extend the Array object and create a helper to do this for you.</p> <pre><code>var ArrayHelper = { sortBy : function(arr, prop){ return function(){ var so = srt.sortOrder == 'asc' ? 1 : -1; var key = srt.sortKey; var result = 0; console.log(srt.sortKey + ' ' + srt.sortOrder + ':'); return function (a, b) { if (srt.isComputed) { result = (a[key]() &lt; b[key]()) ? -1 : (a[key]() &gt; b[key]()) ? 1 : 0; } else { result = (a[key] &lt; b[key]) ? -1 : (a[key] &gt; b[key]) ? 1 : 0; } return result * so; }; } } }; </code></pre> <p>And then in your code...</p> <pre><code>ArrayHelper.sortBy(myItems,sortList[k]); </code></pre> <p>instead of</p> <pre><code>myItems.sortBy(sortList[k]); </code></pre> <p><a href="http://jsfiddle.net/DcN7y/1/" rel="nofollow">Working demo</a></p> <p>For further reading on the subject this <a href="http://perfectionkills.com/extending-built-in-native-objects-evil-or-not/" rel="nofollow">Perfection Kills</a> post discusses whether or not extending native objects is a good idea and you will see it is not a cut and dry issue. Above, I layed out an issue that is not discussed in this blog post but really can cause conflicts with other code.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
 

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