I'm trying to understand how public` properties in the (Revealing) Module Pattern work. An advantage pointed out by Carl Danley "The Revealing Module Pattern" is:
Explicitly defined public methods and variables which lead to increased readability
Let's take a look at this code (fiddle):
var a = function() {
var _private = null;
var _public = null;
function init() {
_private = 'private';
_public = 'public';
}
function getPrivate() {
return _private;
}
return {
_public : _public,
init : init,
getPrivate : getPrivate,
}
}();
a.init();
console.log( a._public ); // null
console.log( a.getPrivate() ); // "private"
It returns null
when calling a._public
. I now can manipulate that public property, like a._public = 'public';
. But I can't change it from within my object. Or at least those changes aren't passed through. I was kinda expecting it to be "public"
as it was updated by the init
-method before.
Does this actually mean, that I can't have any methods, that handle public properties? Then public properties in this pattern make little sense, right? I also tried this without luck (fiddle):
return {
_pubic : _public,
init2 : function() {
_public = 'public';
}
}
Last, but not least, I have a question regarding the whole return
statement. Why isn't it possible to just use return this;
to make everything public? As this
should be the context of the self-invoked function, shouldn't it just return eveyrthing in it? Why do I have to create another object, that is returned? In this fiddle it returns the window
object.