OOP, object literal notation, and the 'new' operator - how to have multiple child objects of a parent object?
I wonder if anyone can clear up an OOP issue for me, specifically, how
to have multiple child objects of a parent object. Consider the code
below:
var parentObj={
childCount: 0,
childObj: {
id:false,
init: function() {
alert(this.id);
parentObj.childCount++;
this.id = parentObj.childCount;
alert("Child " + this.id + " Created");
}
}
}
Calling 'parentObj.childObj.init();', the first alert produces
'undefined' and the second 'Child 1 Created'. A second call to
'parentObj.childObj.init();' produces the '1' from above instead of
the 'undefined' I'm expecting - I realise this is because I'm working
with the same object.
However, calling 'var firstChild = parentObj.childObj.init(); var
secondChild = parentObj.childObj.init()' produces the same result (as
does 'var firstChild = parentObj.childObj; firstChild.init();).
I've also tried the 'new' operator. But the code 'var firstChild =
new parentObj.childObj;' produces the error 'parent.childObjis not a
constructor'.
Thus, you can see I'm missing the point - can anyone point me in the
right direction?