0

I have tree of closures: 'A' containing private closures 'pancake' and 'B'. There is a situation when I need to call from inside of 'B' public function, the private closure of 'A' - 'pancake' and retrieve its public properity. How can I do it? Oh, and this is useless, as this is not an object.

My code:

var A = (function() {
    var pancake = (function() {
        return {
            numeric: 142
        };
    })(A);

    var B = (function() {
        return {
            init: function(name) {                
                console.log(pancake.numeric);
                //How to access the same element using 'name' variable?
            }
        };
    })(A);
    return {
        init: function() {
            B.init('pancake');
        }
    };
})();
A.init();

JSFiddle might show more details: http://jsfiddle.net/yALkY/3/

Thanks in advance

Misiur
  • 5,019
  • 8
  • 38
  • 54
  • 2
    You are using `A` twice before it is initialized. – Mike Samuel Jan 16 '12 at 16:37
  • 1
    Make things into normal objects with public methods. Then, call the desired public method. The code you have included here is way more complicated than required. You can't "call into" private data or a closure unless you expose a public method to do so. – jfriend00 Jan 16 '12 at 16:44
  • I feel more secure using closures than objects (and most the time I don't have problems with them). Could you provide me with an example how to convert this into object? – Misiur Jan 16 '12 at 16:54
  • Though no solution to your problem, but maybe a good read none the less: http://enterprisejquery.com/2010/10/how-good-c-habits-can-encourage-bad-javascript-habits-part-1/ – Yoshi Jan 16 '12 at 16:55
  • http://stackoverflow.com/questions/598878/how-can-i-access-local-scope-dynamically-in-javascript - I finally found something. Anyway thanks for trying, and articles. – Misiur Jan 16 '12 at 17:17

1 Answers1

1

Though I have to aggree with jfriend00 that the given code is over-complicating things, one solution would be to introduce some map to store references in, like:

var A = (function() {
  var pancake = (function() {
      return {
          numeric: 142
      };
  })();

  var B = (function() {
      return {
          init: function(name) {                
              console.log(privateVars[name].numeric);
              //How to access the same element using 'name' variable?
          }
      };
  })();

  // added:
  var privateVars = {
    pancake: pancake 
  };

  return {
      init: function() {
          B.init('pancake');
      }
  };
})();
A.init();

The drawback, of course, is that you'll have to maintain that list manually.

Yoshi
  • 54,081
  • 14
  • 89
  • 103