0

Possible Duplicate:
Is it possible to gain access to the closure of a function?

Please have a look at this code: http://jsfiddle.net/FH6pB/1/

(function($) {
  var o1 = {
    init: function() { alert('1'); },
  }
  var o2 = {
    init: function() { alert('2'); },
  }
}(jQuery));

(function($) {
  var o3 = {
    init: function() { alert('3'); },
  }
  o2.init();
}(jQuery));


o1.init();
o2.init();

I have 3 object in 2 different "scopes" (I don't know if it's the right word to use here, but I guess you understand the meaning). As you probably know, I can't access the objects' function from either outside or other "scope" (non of the o.init(); will work).

Why does it happen? Is there a way to change it?

I know I can just put the code in one scope and it will work well, but what if I have scopes in separate JS file?

Thanks from advance, Ben

Community
  • 1
  • 1
benams
  • 4,308
  • 9
  • 32
  • 74

2 Answers2

1

No, you can't access variables declared in a closure from outside. That's simply how closure work.

A (generally bad) solution, would be to declare the variables as global ones :

(function($) {
  window.o2 = {
    init: function() { alert('2'); },
  };
}(jQuery));

o2.init();

But usually, the module pattern is used to make private some variables and only return the useful ones. See this article.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
1

You could use a namespace-like:

http://jsfiddle.net/FH6pB/2/

var scope = {};

(function($) {
  scope.o1 = {
    init: function() { alert('1'); },
  }
  scope.o2 = {
    init: function() { alert('2'); },
  }
}(jQuery));

(function($) {
  scope.o3 = {
    init: function() { alert('3'); },
  }
  scope.o2.init();
}(jQuery));


scope.o1.init();
scope.o2.init();
A. Wolff
  • 74,033
  • 9
  • 94
  • 155