Is there any way to make “private” variables (those defined in the constructor), available to prototype-defined methods?
TestClass = function(){
var priv
var getParams = function(_func) {
res = _func.toString().split('function (')[1].split(')')[0].split(',')
return res
}
function TestClass(){
var private = {hidden: 'secret'}
//clever magic accessor thing goes here
if ( !(this instanceof arguments.callee) ) {
for (var key in arguments) {
if (typeof arguments[key] == 'function') {
var keys = getParams(arguments[key])
var params = []
for (var i = 0; i <= keys.length; i++) {
if (private[keys[i]] != undefined) {
params.push(private[keys[i]])
}
}
arguments[key].apply(null,params)
}
}
}
}
TestClass.prototype.test = function(){
var _hidden; //variable I want to get
TestClass(function(hidden) {_hidden = hidden}) //invoke magic to get
};
new TestClass().test()
How's this? Using an private accessor. Only allows you to get the variables though not to set them, depends on the use case.