【问题标题】:Creating global API object创建全局 API 对象
【发布时间】:2013-03-13 07:38:49
【问题描述】:

我在 java-script 中使用 module-via-anonymous-function-pattern 来拥有一个匿名函数,它体现了整个模块并通过设置全局属性来公开特定的公共 API 部分。

我尝试了几种设置此类全局属性的方法,但下面发布的第二种方法失败了:

window.foo = (function() {
  function bar() { this.hello = "world" }
  return new bar();
})();

> foo.hello
"world" // OK

对比

(function() {
  window.foo2 = new bar( this.hello = "world" );
  function bar() {}
})();

> foo2.hello
undefined // Fail

为什么第二种方法没有创建正确的条形对象?

【问题讨论】:

  • 超出范围,您应该从返回块中返回对象。
  • new bar( this.hello = "world" ) 看起来很奇怪。
  • pktangyue,是的,先喝杯咖啡吧……对不起

标签: javascript object constructor global


【解决方案1】:

在您的第二种方法中:

(function() {
  window.foo2 = new bar( this.hello = "world" );
  function bar() {}
})();

thiswindow,并且

new bar(this.hello = "world") 

等于

window.hello = "world";
new bar(window.hello);

你可以查看here

我认为你想要的是:

(function() {
  window.foo2 = new bar( "world" );
  function bar(a) {this.hello = a}
})();

here

【讨论】:

    【解决方案2】:

    你应该试试下面的代码

    (function() {
      function bar() { this.hello = "world"; };
      window.foo2 = new bar();
    })();
    

    【讨论】:

    • 呃,你是对的......但是函数可以在词法定义之前被调用,不是吗?
    • @hotzen 但在您的情况下,this.hello = "world" this 是匿名的自我执行功能,而不是吧。
    【解决方案3】:

    问题是使用构造对象的方式。试试这两种方法。

    window.foo2 = new bar();
    function bar() {this.hello = "world";};
    

    window.foo2 = new bar("world");
    function bar(x) {this.hello = x;};
    

    【讨论】:

    • 在第二种情况下,单词“World”存储在 window.hello
    猜你喜欢
    • 1970-01-01
    • 2015-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多