简体   繁体   中英

javascript function sharing between all objects in an array

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.

Let me give you a short example.

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

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:

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

function xySum1(o) {return o.x + o.y;}

objects[0].x       //--> returns 1
objects[0].y       //--> returns 2
xySum1(objects[0]) //--> returns 3

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

Second approach:

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

for (var i=0; i < objects.length; i++) {
    objects[i].xySum2 = function() {return this.x + this.y;};
}

Now, the sum is obtained by

objects[0].x        //--> returns 1
objects[0].y        //--> returns 2
objects[0].xySum2() //--> returns 3

which is much better.

Problems

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

objects.push({x:5,y:21});

then the sum cannot be calculated before the function has been added to the object

objects[3].xySum2() //-->TypeError

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.

Is there a way to do this more efficiently?

Define a class:

function MyObject(x, y) {
    this.x = x;
    this.y = y;
}
MyObject.prototype = {
    xySum2: function() {
        return this.x + this.y;
    }, x: 0, y: 0
};

Then you can do:

var objects = [
    new MyObject(1, 2),
    new MyObject(0, 5),
    new MyObject(3, 14)
];
objects[0].xySum2(); // 3

objects.push(new MyObject(5, 21));
objects[3].xySum2(); // 26

Alternatively, this is what Bergi probably wanted to say in his comment:

objects.xySum = function(index) {
    return this[index].x + this[index].y;
};

This approach is a little bit "dirtier", but also less memory consuming.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM