Alternatively, to modify the Array prototype, as shown in another answer , you can add a method to a specific array (or object) if this works for your case:
function addItem(itemName, quality, quantity /*, arr*/) { this.push([itemName, quality, quantity]); } var someArr = [['item', 1, 1]]; someArr.addItem = addItem; someArr.addItem('someOtherItem', 2, 3); var otherArray = [42]; otherArray.addItem('someOtherItem', 2, 3);
Note that this will not add the method to all arrays (or objects), but only to one specific array that you changed. This can be useful for cases when you add a very specific method (for example, in this case), and not very general, as soon as sum or max , which makes sense for many types of arrays (or objects).
source share