Ok lets break this down
getterTest = (function() {});
getterTest
is a function pointer. i.e. it is a variable that holds the un-envoked function.
If I do:
getterTest = (function() {});
getterTest();
I invoke the function.
If I do:
getterTest = (function() {});
var result = getterTest();
result contains the function returned from the getterTest function, i.e. an object ({}
) that contains a function and a gettable x property
result = {
doSomething: function() {
_x += 5;
},
get x() {
return _x;
}
}
so I could do:
getterTest = (function() {});
var result = getterTest();
result.x;
TL;DR
Really though; what you want is for getterTest
to work like this:
getterTest = function() {
var _x = 15;
return {
doSomething: function() {
_x += 5;
},
get x() {
return _x;
}
}
}();
//invoke the function and store this in your variable by adding () above
//code in file1.js
//console.log(getterTest._x); //this is private so can't be accessed (you can only access things that are returned)
console.log(getterTest.x); //should give 15
getterTest.doSomething();
console.log(getterTest.x); //should give 20
Fiddle
You cannot access _x outside of the closure, because it's scope is the function. This is , essentially, the point of closures. To keep things in scopes and to keep the "global context" clean.
FYI
You might notice I kinda use "function" and "object" interchangeably in the above. People not used to Javascript find this odd but there is a good reason. In Javascript a function is an object o_O
Again this is one of the principals of what your trying to achieve here. It's all basically about encapsulation