javascript function sharing between all objects in an array
<p>I'm trying to add a function to an array of objects, which each object has access to, but which does not need to be added to each object separately. </p>

<p>Let me give you a short example.</p>

<p>Let's say I have an array containing similar objects, each having a property x and a property y:</p>

<pre><code>var objects = [{x:1, y:2},
               {x:0, y:5},
               {x:3, y:14}
              ];
</code></pre>

<p>I would like to calculate the sum of <code>x</code> and <code>y</code> for any of the objects.</p>

<p><strong>First approach:</strong></p>

<p>In order to calculate the sum for a given object, one could pass this object to a predefined function like so:</p>

<pre><code>function xySum1(o) {return o.x + o.y;}

objects[0].x       //--&gt; returns 1
objects[0].y       //--&gt; returns 2
xySum1(objects[0]) //--&gt; returns 3
</code></pre>

<p>This is quite ugly and unsatisfactory, as accessing the <code>x</code> and <code>y</code> properties is done differently. Also, my code is in different locations and the function <code>xySum1</code> is not easily recognizable as being created to act on the objects in the array.</p>

<p><strong>Second approach:</strong></p>

<p>One could loop through the array and add the function as a property to each object:</p>

<pre><code>for (var i=0; i &lt; objects.length; i++) {
    objects[i].xySum2 = function() {return this.x + this.y;};
}
</code></pre>

<p>Now, the sum is obtained by</p>

<pre><code>objects[0].x        //--&gt; returns 1
objects[0].y        //--&gt; returns 2
objects[0].xySum2() //--&gt; returns 3
</code></pre>

<p>which is much better.</p>

<p><em>Problems</em></p>

<p>There are, however, problems with this approach. Firstly, when I add a new element to the array</p>

<pre><code>objects.push({x:5,y:21});
</code></pre>

<p>then the sum cannot be calculated before the function has been added to the object</p>

<pre><code>objects[3].xySum2() //--&gt;TypeError
</code></pre>

<p>Another problem is that I have many objects, and many functions to add to them. It seems like a waste of good memory space to add each function to each objects individually. </p>

<p>Is there a way to do this more efficiently?</p>
