Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
44
rated 0 times [  49] [ 5]  / answers: 1 / hits: 37344  / 10 Years ago, sat, november 8, 2014, 12:00:00

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


More From » jquery

 Answers
32

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

[#68863] Thursday, November 6, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
manuel

Total Points: 747
Total Questions: 96
Total Answers: 95

Location: Argentina
Member since Thu, Mar 18, 2021
3 Years ago
;