Marcin Skibiński
Marcin Skibiński

Reputation: 33

Javascript object as parent for another js object

Could you explain me how to do in JavaScript such thing :

  1. Create one object.
  2. Create second object.
  3. Set first object as a parent to second object.
  4. Add second object as child to first object.

It sounded simple to me as Java developer but I am confused right now.

Demo:

var childFunction = function(parent){
    this.parent = parent;
    this.value = 14;
    this.fun = function(){
        document.getElementById("test").innerHTML=parent.value;
    };
    this.setParent = function(parent){
        this.parent = parent;
    }
}

var parentFunction = function(){
    this.value=20;
    this.child=''; 
    
    this.addChild = function(child){
        child.setParent(this);
        this.child=child; 
    }
    
    this.setchild = function(child){
        this.child = child;
    }
    this.createChild= function(){
        this.child = new childFunction(this);
    }
}


var par = new parentFunction();
var ch = new childFunction('');
//par.setchild(new childFunction(par));
//par.createChild();
par.addChild(ch);

par.child.fun();
<div id="test"></div>

Upvotes: 0

Views: 80

Answers (2)

Davin Tryon
Davin Tryon

Reputation: 67316

The current code does not pass the parent to the child in the child's constructor.

As @Axel point's out in his answer, the cause of the issue is that the variable parent is not bound to anything, unless you pass in a parent in the constructor's parameter named parent. By passing in parent in the child's constructor, you create a closure for this line:

document.getElementById("test").innerHTML=parent.value;

This has been fixed below:

var childFunction = function(parent){
    this.parent = parent;
    this.value = 14;
    this.fun = function(){
        document.getElementById("test").innerHTML=parent.value;
    };
    this.setParent = function(parent){
        this.parent = parent;
    }
}

var parentFunction = function(){
    this.value=20;
    this.child=''; 
    
    this.addChild = function(child){
        child.setParent(this);
        this.child=child; 
    }
    
    this.setchild = function(child){
        this.child = child;
    }
    this.createChild= function(){
        this.child = new childFunction(this);
    }
}


var par = new parentFunction();
var ch = new childFunction(par);  //<-- pass parent in child constructor

par.addChild(ch);

par.child.fun();
<div id="test"></div>

Upvotes: 1

Axel Amthor
Axel Amthor

Reputation: 11106

It's working as of this fiddle as soon as you change:

 document.getElementById("test").innerHTML=this.parent.value;

Upvotes: 2

Related Questions