Reputation: 33
Could you explain me how to do in JavaScript such thing :
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
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
Reputation: 11106
It's working as of this fiddle as soon as you change:
document.getElementById("test").innerHTML=this.parent.value;
Upvotes: 2