Add a function as a method of a native Array object (is it possible to call a function as a method?)

I feel that maybe something is incredibly simple that I missed in MDN docs or something like that, but I dug for a while and I have no idea.

Is there a way to call a function similarly to a method? This is basically what I'm trying to do:

function addItem(itemName, quality, quantity /*, arr*/) { arr.push([itemName, quality, quantity]); } var someArr = [['item', 1, 1]]; someArr.addItem('someOtherItem', 2, 3); // someArr === [['item', 1, 1], ['someOtherItem', 2, 3]] 

Now, of course, I'm not trying to create a constructor or define a variable as a function. In addition, I fully understand that I can just add an array as an argument and call the function as usual. What I'm trying to execute is to run the function in such a way that when it is marked as an array method, it will affect this array in the specified way. How can i do this? Can I do this at all?

+5
source share
2 answers

DANGEROUS APPROACH (disclaimer: P):
I am not a supporter of the expansion of native facilities, so the following solution serves only as one of the ways to achieve this goal, but is very discouraged in practice. See: DANGERS OF EXPANSION OF PEOPLE'S OBJECTS

 Array.prototype.addItem = function addItem(itemName, quality, quantity) { this.push([itemName, quality, quantity]); } var someArr = [['item', 1, 1]]; someArr.addItem('someOtherItem', 2, 3); console.log(someArr); // logs out: [["item", 1, 1], ["someOtherItem", 2, 3]] 

Using this inside a new method with setting the object to which the method is called. In the case of this example, this will be an array of someArr .


BEST APPROACH: Extend Array Instance someArr using addItem (and NOT a native Array object):

 var someArr = [['item', 1, 1]]; // set property 'addItem' on someArr to equal named function expression someArr.addItem = function addItem(itemName, quality, quantity) { this.push([itemName, quality, quantity]); }; someArr.addItem('someOtherItem', 2, 3); console.log(someArr); // logs out: [["item", 1, 1], ["someOtherItem", 2, 3]] 
+3
source

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); // fails as otherArray does not have addItem. 

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).

+2
source

Source: https://habr.com/ru/post/1265912/


All Articles