OOP, the new operator & object literal notation - multiple child objects of a parent

Discussion in 'JavaScript' started by iporter, Oct 18, 2007.

  1. #1
    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, Oct 18, 2007 IP
  2. webmaster_TSU

    webmaster_TSU Peon

    Messages:
    449
    Likes Received:
    9
    Best Answers:
    0
    Trophy Points:
    0
    #2
    I'm not really sure, but the first alert should produce a false all the time, right? So when you call it again, you get a 1 for true?

    I think you would need to do a var firstParent = new parentObj; first, then try to create a child, var firstChild = firstParent.childObj.init(); maybe. The way it seems now, there is only one child per parent, though, you might need a list of children.
     
    webmaster_TSU, Oct 18, 2007 IP