简体   繁体   English

Javascript从字符串访问嵌套闭包公共函数,而无需使用“ this”

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

I have tree of closures: 'A' containing private closures 'pancake' and 'B'. 我有闭包树:“ A”包含私有闭包“ pancake”和“ 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. 在某些情况下,我需要从“ B”公共功能内部调用,“ A”的私有闭包-“薄煎饼”并获取其公共属性。 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/ JSFiddle可能会显示更多详细信息: 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: 尽管我必须同意jfriend00同意给定的代码使事情变得过于复杂,但是一种解决方案是引入一些映射来存储引用,例如:

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. 缺点当然是您必须手动维护该列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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