Is there any way to make “private” variables (those defined in the constructor), available to prototype-defined methods?
TestClass = function(){
var priv
I faced the exact same question today and after elaborating on Scott Rippey first-class response, I came up with a very simple solution (IMHO) that is both compatible with ES5 and efficient, it also is name clash safe (using _private seems unsafe).
/*jslint white: true, plusplus: true */
/*global console */
var a, TestClass = (function(){
"use strict";
function PrefixedCounter (prefix) {
var counter = 0;
this.count = function () {
return prefix + (++counter);
};
}
var TestClass = (function(){
var cls, pc = new PrefixedCounter("_TestClass_priv_")
, privateField = pc.count()
;
cls = function(){
this[privateField] = "hello";
this.nonProtoHello = function(){
console.log(this[privateField]);
};
};
cls.prototype.prototypeHello = function(){
console.log(this[privateField]);
};
return cls;
}());
return TestClass;
}());
a = new TestClass();
a.nonProtoHello();
a.prototypeHello();
Tested with ringojs and nodejs. I'm eager to read your opinion.