0

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>

2
  • Check what this references in each case, you might be surprised. Commented May 9, 2015 at 9:18
  • Code seems to be proper, what are your current issues? Commented May 9, 2015 at 9:21

2 Answers 2

2

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

 document.getElementById("test").innerHTML=this.parent.value;
Sign up to request clarification or add additional context in comments.

Comments

1

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.