The title is really confusing, I couldn't find a better one.
Suppose I have:
var A = function (){
this.pa = { x: 1 };
};
A.prototype.B = function (){
this.pb = /* a reference to { x: 1 } */;
};
var a = new A ();
var b = new a.B ();
console.log (b.pb.x); //should print 1
a.pa.x = 2;
console.log (b.pb.x); //should print 2
I want to save in pb a reference to the pa object. Is it possible?
A function used as a constructor has only a reference to the new instance, inheriting from its prototype.
To make it maintain a reference to the original A instance, you will need to put the B constructor in a closure:
function A() {
var that = this;
this.pa = { x: 1 };
this.B = function() {
this.pb = that.pa;
};
};
var a = new A ();
var b = new a.B ();
console.log (b.pb.x); // does print 1
a.pa.x = 2;
console.log (b.pb.x); // does print 2
However, this has the disadvantage of creating a new B constructor (with its own prototype object) for every single A instance. Better would be something like
function A() {
this.pa = { x: 1 };
}
A.B = function() {
this.pb = null;
};
A.prototype.makeB = function() {
var b = new A.B();
b.pb = this.pa;
return b;
};
// you can modify the common A.B.prototype as well
var a = new A ();
var b = a.makeB();
console.log (b.pb.x); // does print 1
a.pa.x = 2;
console.log (b.pb.x); // does print 2
Yet, we could mix the two approaches so that you have only one prototype but different constructors:
function A() {
var that = this;
this.pa = { x: 1 };
this.B = function() {
this.pb = that.pa;
};
this.B.prototype = A.Bproto;
}
A.Bproto = {
…
};
var A = function (){
this.pa = { x: 1 };
};
A.prototype.B = function (a){
this.pb = a.pa;
};
var a = new A ();
var b = new a.B(a);
console.log(b.pb.x); //should print 1
a.pa.x = 2;
console.log(b.pb.x);
Well, it's not exactly what I want but it's very close:
var A = function (pa){
this.pa = pa;
};
A.prototype.B = function (a){
if (this instanceof A.prototype.B){
if (!a) throw "error";
this.pb = a.pa;
return;
}
return new A.prototype.B (this);
};
var a = new A ({ x: 1 });
var b = a.B ();
console.log (b.pb.x); //1
a.pa.x = 2;
console.log (b.pb.x); //2
new a.B () //throws "error"