【发布时间】: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