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++;
};