www.webdeveloper.com
Results 1 to 3 of 3

Thread: Object-oriented JavaScript - Parent/Child objects

  1. #1
    Join Date
    Sep 2010
    Posts
    2

    Question Object-oriented JavaScript - Parent/Child objects

    I'm just starting to get deeper in JavaScript programming, in particular OO and prototyping, and have run into a problem. I want to create some 'container' objects with themselves contain 'item' objects...

    Code:
    function container() {
       this.width = '400';
       this.height = '600';
       this.color = 'white';
    }
    
    function item() {
       this.heading = 'Item';
       this.text = 'Default item text';
    }
    
    var containerA = new container();
    containerA.color = 'red';
    
    var containerB = new container();
    containerB.color = 'green';
    
    // I want these in containerA.
    var itemA = new item();
    var itemB = new item();
    
    // I want these in containerB.
    var itemC = new item();
    var itemD = new item();
    So now I have two 'container' objects and four 'item' objects. How would I go about adding itemA and itemB to containerA, and itemC and itemD to containerB?

    I have some ideas... perhaps I need some sort of item array var in the container object? Or perhaps I need a parentContainer var in the item object. Then if I loop through them I can programmatically add them.

    I would like to be able to shift items to other containers also.

    I hope this is making sense and someone can offer me some guidance!

  2. #2
    Join Date
    Sep 2010
    Posts
    2
    I was just thinking ~ is there a way to do this?

    Code:
    var containerA = new container();
    var containerA.itemA = new item();
    var containerA.itemB = new item();
    In affect, just creating as many item objects I want within the container object? I don't know if I'm heading in the right direction

  3. #3
    Join Date
    Jan 2003
    Location
    Texas
    Posts
    10,413
    Quote Originally Posted by ShoopDaWoop View Post
    I was just thinking ~ is there a way to do this?

    Code:
    var containerA = new container();
    var containerA.itemA = new item();
    var containerA.itemB = new item();
    In affect, just creating as many item objects I want within the container object? I don't know if I'm heading in the right direction
    Correct. You can assign (nest) a new object as a property of an existing object.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles