On Oct 18, 11:39 pm, iporter <ispor...@gmail.com> wrote:
> 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);
When init is called as a method of childObj, the function's this
keyword will be set as a reference to childObj.
> parentObj.childCount++;
> this.id = parentObj.childCount;
And here you set childObj.id to the value of the recently incremented
childCount.
> alert("Child " + this.id + " Created");
> }
> }
> }
>
> Calling 'parentObj.childObj.init();', the first alert produces
> 'undefined'
For me it shows false in both IE and Firefox.
> 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.
Why would you expect it to be 'undefined' when a direct consequence of
calling parentObj.childObj.init is to set the id property of
parentObj.childObj to parentObj.childCount, which you increment each
time the init function is called?
> However, calling 'var firstChild = parentObj.childObj.init(); var
> secondChild = parentObj.childObj.init()'
Given that the function doesn't return anything, the value of
firstChild and secondChild will be undefined.
> produces the same result (as
> does 'var firstChild = parentObj.childObj; firstChild.init()
.
Which result is that? The result of calling the function twice will
not change just because you assign the results to different variables.
> I've also tried the 'new' operator. But the code 'var firstChild =
> new parentObj.childObj;' produces the error 'parent.childObjis not a
> constructor'.
Precisely. The new operator expects to be used with a function, not a
plain object.
> Thus, you can see I'm missing the point - can anyone point me in the
> right direction?
If I had any idea what that might be I'd try, hopefully the above will
help you to ask a question that can be answered more precisely.
It seems to me that your issue is not creating an object structure,
but understanding how the value of a function's this keyword is set.
Try this thread:
<URL:
http://groups.google.com.au/group/co...34df52136d6a13
>
--
Rob