I am trying to add a function to an array of objects to which each object has access, but which does not need to be added to each object separately.
Let me give you a short example.
Let's say I have an array containing similar objects, each of which has the x property and the y property:
var objects = [{x:1, y:2}, {x:0, y:5}, {x:3, y:14} ];
I would like to calculate the sum of x and y for any of the objects.
First approach:
To calculate the sum for a given object, you can pass this object to a predefined function, for example:
function xySum1(o) {return ox + oy;} objects[0].x
This is pretty ugly and unsatisfactory since the access to the x and y properties is done differently. In addition, my code is in different places, and the xySum1 function xySum1 not easily recognized as created for working with objects in an array.
Second approach:
You can go through the array and add a function as a property for each object:
for (var i=0; i < objects.length; i++) { objects[i].xySum2 = function() {return this.x + this.y;}; }
Now the amount is obtained through
objects[0].x //--> returns 1 objects[0].y //--> returns 2 objects[0].xySum2() //--> returns 3
which is much better.
Problems
However, there are problems with this approach. First, when I add a new element to the array
objects.push({x:5,y:21});
then the amount cannot be calculated before the function is added to the object
objects[3].xySum2()
Another problem is that I have many objects and many functions to add them. It seems that lost useful memory allows you to add each function to each object individually.
Is there a way to do this more efficiently?