I’m missing something in understanding how js works. here’s the problem:
We declare a module like this:
ns.obj = function() {
// declare private variables
var test = 1, test1 = 2;
// declare some private function
var myFunc=function(){test=2};
return{test:test, myFunc:myFunc};
}
Every time myFunc is called, as we are not declaring test inside the function js should assume we are referring to the private variable.
The returned object makes sure we have test and myFunc visible if we have the module. So calling ns.obj.test should give us 1 at first. And after we call myFunc should give us 2. But it`s always 1. Why that happens?
here’s the jsfiddle: http://jsfiddle.net/aXuwB/1/
In JavaScript overwriting a variable does not overwrite it anywhere else. You’re effectively passing the number 1 in your return object; there is no reference to the
testvariable.An option you have is returning a function. A function holds code and thus can hold a reference to a variable. Calling it would give you the variable:
test: function() { return test; }.