It appears you have not yet registered with DEVPPL. To register please click here... (it's fast, easy and free!)

Forum

Log In Sponsors
Board index Programming JavaScript Forum

OOP, the new operator & object literal notation

OOP, the new operator & object literal notation

Postby iporter on Thu Oct 18, 2007 1:34 pm

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?
iporter
 
Posts: 0
Joined: Thu Oct 18, 2007 1:27 pm

Who is online

Users browsing this forum: No registered users and 7 guests