Basically what I am trying to do is write a re-useable getter/setter to expose variables using the module pattern
// the getter/setter
function pub (variable) {
return function (value) {
return (arguments.length ? variable = value : variable);
}
}
var module = (function () {
var publicVariable = 0;
function test () {
return publicVariable;
}
return {
publicVariable: pub(publicVariable),
test: test
}
})();
The desired result is the following:
module.publicVariable(); // 0
module.publicVariable(1); // 1
module.publicVariable(); // 1
module.test(); // 1
But instead I get:
module.publicVariable(); // 0
module.publicVariable(1); // 1
module.publicVariable(); // 1
module.test(); // 0
I assume this is because the following line passes the current value of publicVariable to pub, therefore the only closure created is the one inside pub and there is no link to the variable itself.
publicVariable: pub(publicVariable), // same as "pub(0)"
I know there is no way to pass by reference in javascript. So how else can I accomplish what I am trying to do? I do not care whether props are called by function or property.
i.e. either of the following are fine
module.publicVariable = "new value";
module.publicVariable("new value");
I am just getting really tired of writing:
function prop1f (value) { return (arguments.length ? prop1 = value : prop1); }
function prop2f (value) { return (arguments.length ? prop2 = value : prop2); }
function prop3f (value) { return (arguments.length ? prop3 = value : prop3); }
return {
prop1: prop1f,
prop2: prop2f,
prop3: prop3f
}
as this gets unruly quick on large projects with lots of user accessible properties.