Update:
This kind of implementation is simply bad, and I've removed that answer.
I just answered this question. The OP asked for the solution of a private member which can only be accessible by prototype methods. For my answer, I would not suggest to do that but propose the code of its possibility. (And sorry, I do not have a good idea with the title .. )
Code
function A(prop1) { var myFunc=A.prototype.myFunc; var that=this; A.prototype.myFunc=function () { if (this===that) { alert(prop1); // do something } else { myFunc.call(this); } }; this.retire=function () { that=undefined; }; } A.prototype.myFunc=function () { }; var a1=new A(1); var a2=new A(2); var a3=new A(3); a1.myFunc(); a2.myFunc(); a3.myFunc(); a2.retire(); a1.myFunc(); a2.myFunc(); a3.myFunc(); // ..
As we can see if any other prototype methods would access prop1
, will need to repeat this pattern. I've ever thought about to use a private array to achieve it, but this code seems significantly shorter.
But there are things not good:
- It needs an extra function to ensure
that
not reference tothis
. A.prototype.myFunc
is growing up(deeper) with the object creation afterwards.- As every
var myFunc
are still referenced byA.prototype.myFunc
, there's a doubt even after invokedretire
and clean up all outter reference to an object, it might still alive when the gc comes. - I have limited testing environment and be pleasure to know if there's potential risk with this implementation.
So I think an answer to the question could be:
A. A more feasible approach to alter the prototype methods in the constructor to achieve that the private members can only be accessible in prototype methods.
B. Another method to achieve the same thing, and the code is as simple as possible.
It would also be greatly appreciated to point out my misunderstanding of the closures and the garbage collection within your answers.