0

In my app, I have the following closure. It contains a var, which is initialized in $(document).ready:

var myClosure = (function() {
  var thing;

  $(document).ready(
    function() {
      thing = new ClassDefinedInSomeOtherFile();
    }
  )

  return {
    thing: thing
  };
})();

As the page loads (I debug in chrome), a breakpoint placed in $(document).ready() is reached and I can see thing get assigned to an object of ClassDefinedInSomeOtherFile.

However, elements attempting to subsequently access myClosure.thing encounter errors stating that myClosure.thing is undefined (as do calls from the console to myClosure.thing). If thing was exposed by the return block in myClosure, why does it not reflect the new value assigned to it, when $(document).ready() ran?

Thanks!

stackleit
  • 264
  • 4
  • 13
  • 1
    `$(document).ready()` runs asynchronously. The variable isn't assigned yet when you execute the `return` statement. – Barmar Nov 04 '15 at 21:39

1 Answers1

0

you are using IIFE so gets executed immediately and return { thing: undefined}, after that when .ready event triggers, it runs and change thing, but that wont change the returned object, so you would get myClosure.thing is undefined

Solution:

$(document).ready(function() {
 var myClosure = (function() {
  var thing;
  thing = new ClassDefinedInSomeOtherFile();
  return {
    thing: thing
  };
 })()
});
vinayakj
  • 5,591
  • 3
  • 28
  • 48