Jinu Joseph Daniel
Jinu Joseph Daniel

Reputation: 6291

Javascript Module pattern. How to access globals inside the module

I have seen the following code

var MODULE = (function () {
var my = {},
    privateVariable = 1;

function privateMethod() {
    // ...
}

my.moduleProperty = 1;
my.moduleMethod = function () {
    // ...
};

return my;
 }());

the properties can be accessed like MODULE.moduleProperty ...right? But how to access globals privateVariable and privateMethod() inside the module(which are globals insode the module ...right?)

Upvotes: 0

Views: 129

Answers (2)

Adam Jenkins
Adam Jenkins

Reputation: 55792

You can only access them from WITHIN the module code itself as such:

var MODULE = (function () { 
 var my = {},
 privateVariable = 1;
 function privateMethod() {
  alert('this is private!');
 }

 my.moduleProperty = 1;
 my.moduleMethod = function () {
  privateMethod();
  return privateVariable;
 };
 return my;
}());

Doing this:

MODULE.moduleMethod();

Will call private method (and alert 'this is private!') and return the value of privateVariable.

There is no way to access privateVariable or privateMethod outside the MODULE scope.

var MODULE = (function() {
 //...declare your module as above
}());

console.log(MODULE.privateVariable); //logs undefined

Hopefully that helps clear it up for you.

Upvotes: 1

Guffa
Guffa

Reputation: 700800

No, they are not global, they are local variables inside the anonymous function.

You can access them from any code within the function, but outside the function they are not directly accessible.

Upvotes: 1

Related Questions