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

2
  • There is no code in the fiddle. Commented Jan 13, 2013 at 15:35
  • 2
    Please don't only put your code in the fiddle, put it in the question too. Commented Jan 13, 2013 at 15:36

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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();

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.