【问题标题】:How to pass external variables to a private javascript outer closure function?如何将外部变量传递给私有 javascript 外部闭包函数?
【发布时间】:2010-12-18 13:41:13
【问题描述】:

我可能在这个上做了一些糟糕的设计选择。我有几个像这样实例化的对象。

core.modules.trial = function(sandbox){
  return{
    alert_private : function(){
      alert(omgpi);
    }
  };
};

我想这样做:

   core.modules.trial[omgpi] = "external private var";

    var trial = core.modules.trial();

    trial.alert_private(); //would hopefully output "external private var"

我正在尝试将 omgpi 变量分配给外部函数的私有范围。通常你会在返回任何东西之前在外部函数中执行 var omgpi 。但是当调用此函数时,我试图从外部脚本执行此操作

【问题讨论】:

  • 不修改 core.modules.trial,afaik 你只能用全局变量 (window.omgpi) 来做到这一点

标签: javascript design-patterns oop closures


【解决方案1】:

如果您需要 omgpi 在闭包中,则需要从内部进行设置。你不能在你不参与的闭包中设置东西。

core.modules.trial = function(sandbox){

    ///////////////////////////
    var omgpi = this.omgpi;
    ///////////////////////////

    return{
        alert_private : function(){
            alert(omgpi);
        }
    };
};

但每当您调用 core.modules.trial() 时,this 指的是 modules,因为这就像父级一样。因此,您可以像这样将值粘贴在模块中:

core.modules.omgpi = "external private var";

然后剩下的工作:

var trial = core.modules.trial();
trial.alert_private(); // alerts "external private var"

顺便说一句,您的原始代码有一个错误:

core.modules.trial[omgpi]

这使用变量 omgpi 的 值 作为键。你想要core.modules.trial.omgpi 或core.modules.trial["omgpi"]。

【讨论】:

  • thx darkporter,我有很多与 .trial 类似的模块,我试图避免在其中重复代码。有什么方法可以在 .modules 对象或核心中自动执行此 var 分配?以便各个模块继承它?
  • 我怀疑这段代码可以方式简化。在您的示例中,trial 是否会以不同的 omgpi 值多次调用? IE。你会这样做吗: core.modules.omgpi = "external private var"; var trial = core.modules.trial(); ... 稍后 ... core.modules.omgpi = "新值"; var otherTrial = core.modules.trial();
【解决方案2】:

你可以猴子补丁 core.modules.trial:

var old_constructor = core.modules.trial;
core.modules.trial = function(sandbox) {
  this.omgpi = 'whatever'; // or an object you can add to as desired
  return old_constructor.call(this, sandbox); // rebinds to this this
};

请参阅call 的文档。

【讨论】:

  • 这不起作用,因为 omgpi 被称为外部符号。你试过了吗?
  • 这与我想要完成的非常接近,但我不必在公共方法中预先添加所有内容吗? gpilontino 也是正确的,但这是行不通的。
【解决方案3】:
core.modules.trial = function(sandbox){
  var self = {
    alert_private: function(){
      alert(self.omgpi);
    }
  };

  return self;
};

【讨论】:

    【解决方案4】:

    这是你想要的吗?

    core.modules.trial = function(sandbox){
      var c = arguments.callee;
      return{
        alert_private : function(){
          alert(c.omgpi);
        }
      };
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-14
      • 2014-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多