array as data member in a class javascript

user3316523 picture user3316523 · Nov 8, 2014 · Viewed 27.6k times · Source

I am new one in object oriented javascript and trying to define a class, that have an array as a data member. this data member of class storing objects of an other class as an array.

it will be more clear by this example

function classA(id, objB_01)
{

    this.id = id;   // data member that store a simple value
    this.arrayname = objB_01  // How multiple instance of classB is stored in this array 


}

function classB( id, name, status)
{
     this.id = id;
     this.name = name;
     this.status = status 
}

objB_01 = new classB("01", "john", "single");
objB_02 = new classB("02", "smith" "single");
objB_03 = new classB("03", "nina", "married");

now my question is how i can write classA so that single instance of classA hold an array that store mutiple object of classB

Something like this

objA = new classA("01",objB_01);
objA.arrayname = objB_02;
objA.arrayname = objB_03;

Now Finally objA contain one string and one array that store multiple objects of classB

Please point me in the right direction

Answer

meir shapiro picture meir shapiro · Nov 8, 2014

One option can be to initialize an empty array in the constructor function and also have some method to add objects to the array.

function classA (id) {
    this.id = id;
    this.array = [];

    this.add = function (newObject) {
        this.array.push(newObject);
    };
}

Then you can do this:

objA = new classA("01");
objA.add(objB_01);
objA.add(objB_02);
objA.add(objB_03);