4

我正在使用 ADVANCED_OPTIMIZATIONS 编译级别的 Google Closure Compiler 并开始注释我的构造函数,因为我收到了各种警告:

警告 - 危险地使用全局 this 对象

对于我的“构造函数”类型函数,我将像这样注释它们:

/**
 * Foo is my constructor
 * @constructor
 */
Foo = function() {
   this.member = {};
}

/**
 * does something
 * @this {Foo}
 */
Foo.prototype.doSomething = function() {
   ...
}

这似乎工作正常,但是如果我有一个不是用 var myFoo = new Foo(); 构造​​的“单例”对象怎么办?我在文档中找不到如何注释这种类型的对象,因为它的类型只是对象,对吗?

Bar = {
   member: null,
   init: function() {
      this.member = {};
   }
};
4

2 回答 2

9

在 Closure 中创建单例的首选方式是这样的:

/** @constructor */
var Bar = function() { };
goog.addSingletonGetter(Bar);

Bar.prototype.member = null;

Bar.prototype.init = function() {
  this.member = {};
};

这允许对单例进行延迟实例化。像这样使用它:

var bar1 = Bar.getInstance();
var bar2 = Bar.getInstance();

bar1.init();
console.log(bar2.member);

请记住,这不会阻止人们使用构造函数来创建Bar.

于 2011-04-16T16:13:07.370 回答
5

正是“危险使用此”警告您注意的潜在错误类型。在您的示例中,闭包编译器可能会尝试将您的代码“扁平化”为:

Bar$member = null;
Bar$init = function() { this.member = {}; };

注意:闭包编译器目前不会展平声明为全局对象的命名空间(即前面没有“var”关键字),因此您的代码现在可能仍然可以工作。但是,没有人知道它在未来的版本中不会这样做,并且您的代码会突然中断而没有警告。

当然,那么“Bar$member”和“Bar$init”将分别重命名为“a”和“b”。这称为“命名空间扁平化”或“属性折叠”。

您可以立即看到您的代码不再正常工作。在编译之前,如果你写:

Bar.init();

this将参考Bar。但是,编译后变成:

Bar$init();

this将不再提及Bar。相反,它指的是全局对象。

这是编译器试图警告您以这种方式使用“this”是“危险的”的方式,因为“this”可能会更改为引用“全局”对象。这就是警告的真正含义。

简而言之,不要这样做。这种类型的编码风格会产生很难追踪的错误。

以这种方式修改您的代码:

var Bar = {    // Closure Compiler treats globals and properties on global differently
  member: null,
  init: function() { Bar.member = {}; }
};

或使用闭包:

var Bar = (function() {
  var member = null;
  return {
    init: function() { member = {}; }
  };
})();

在高级模式下使用闭包编译器时,不要试图通过注释掉警告来摆脱它们。警告是有原因的——它们试图警告你一些事情。

于 2011-04-17T03:41:18.680 回答