【问题标题】:function returning constructor and calling directly函数返回构造函数并直接调用
【发布时间】:2015-10-20 19:05:15
【问题描述】:

我目前正在用 Javascript 编码并调用一个返回构造函数的函数,我想立即创建这样的对象。但我不工作。因为我希望这段代码在一行中,而不必创建另一个 var 来启动它。 提前致谢。

this.vendor = new Lib.vendorAPI.retreiveVendor(this.vendorConst)(this);

这样可以工作,但不是内联的。

var currentVendor = new Lib.vendorAPI.retreiveVendor(this.vendorConst)(this);
this.vendor = new currentVendor(this);

提前致谢。

【问题讨论】:

  • “因为我想把这段代码放在一行中” - 为了想要而牺牲可读性?嗯……
  • 在这种情况下,内联编写它更简洁,否则您将使用变量 currentVendor 和 this.vendor。但是当你说可读性更难时,我支持你。这是真的。

标签: javascript constructor inline short


【解决方案1】:

自己找到了答案: 在函数周围添加括号将告诉浏览器它首先需要执行函数,然后从返回的构造函数创建实例。 像这样:

this.vendor = new (Lib.vendorAPI.retreiveVendor(this.vendorConst))(this);

【讨论】:

    【解决方案2】:

    怎么样

    var currentVendor = new new Lib.vendorAPI.retreiveVendor(this.vendorConst)(this);
    

    【讨论】:

      猜你喜欢
      • 2013-10-03
      • 2013-09-23
      • 2017-09-28
      • 2012-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-08
      • 1970-01-01
      相关资源
      最近更新 更多