简体   繁体   中英

Javascript accessing nested closure public function from string without using 'this'

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM