简体   繁体   中英

Creating an array of other objects in javascript?

Is something like this possible:

function FooClass()
{
   var barsArray=new Array();
   var index=0;

   function addBar()
   {
     barsArray[index]=new BarClass(index);
   }
}

function BarClass()
{
   var myIndex;
   function BarClass(index)
   {
      myIndex=index;
   }
}

I'm inferring that you want to have a Foo object, and that Foo object should contain an array of Bar objects. Each Bar object should know its array index within its parent Foo object.

If that is an accurate description, then try this:

function BarClass(idx) {
    this.myIndex = idx;
}

function FooClass(howMany) {
    this.barsArray = [];

    for (var x = 0; x < howMany; x++) {
        this.barsArray[x] = new BarClass(x);
    }

}

var foo = new FooClass(5);
// foo.barsArray[0].myIndex === 0
// foo.barsArray[1].myIndex === 1
// foo.barsArray[2].myIndex === 2
// foo.barsArray[3].myIndex === 3
// foo.barsArray[4].myIndex === 4
// foo.constructor === 'FooClass'
// foo.barsArray[0].constructor === 'BarClass'

Good luck!

Not quite (actually it compiles, but probably doesn't do what you intended).

I'm assuming you want to create a FooClass class with an addBar method that appends a BarClass object to it's barsArray member.

The addBar function is just a local variable inside the FooClass function/constructor. To make it accessible from outside the constructor, you need to assign it to this.addBar . Other than remembering to increment index , that's all you would need to change in FooClass .

For the BarClass class, remember that a "class" is really just a constructor function. You don't need to (and can't) a separate constructor. BarClass would just be a single function that takes an index and assigns it to this.myIndex .

function FooClass()
{
   // use this.barsArray = [], etc if you want them to be publically available
   var barsArray=[]; // It's usually better to use "[]" instead of "new Array()"
   var index=0;

   this.addBar = function() {
     barsArray[index]=new BarClass(index);
     index++;
   }
}

function BarClass(index)
{
   this.myIndex=index;
}

If you change barsArray and index to be properties instead of local variables ("this.barsArray = [];" and "this.index = 0"), you can put addBar in FooClass.prototype and there will only be one instance of the function:

function FooClass()
{
   this.barsArray=[];
   this.index=0;
}

FooClass.prototype.addBar = function() {
   this.barsArray[this.index]=new BarClass(this.index);
   this.index++;
};

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