When implementing the module pattern, how do private functions access the private properties of the module? I haven't seen any examples where developers do this. Is there any reason not to?
var module = (function(){
// private property
var number = 0;
// private method
_privateIncrement = function(){
// how do I access private properties here?
number++;
};
// public api
return {
// OK
getNumber: function(){
return number;
},
// OK
incrNumber: function(){
number++;
},
// Doesn't work. _privateIncrement doesn't have
// access to the module's scope.
privateIncrNumber: function(){
_privateIncrement();
}
};
})();
One alternative to have private methods with access to the
this
is by using thecall
orapply
methods.Of course you would move the use_restroom and buy_food to a prototype and private_stuff outside of the constructor if you were planning on having multiple instances of this object.
The properties are in scope, so they "just do"
Yes, it does.
Yes, it does.
See live example of the following: