javascript - Annotate Singleton objects in JavaScript for the Google Closure Compiler, 或 "dangerous use of the global this object"警告

标签 javascript google-closure-compiler jsdoc

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

WARNING - dangerous use of the global this object

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

/**
 * 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 = {};
   }
};

最佳答案

在 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 的实例。

关于javascript - Annotate Singleton objects in JavaScript for the Google Closure Compiler, 或 "dangerous use of the global this object"警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5687633/

相关文章:

javascript - 使用 JSDoc 标记已弃用的类

javascript - jQuery noconflict、bootstrap 和 requirejs

javascript - DataTables - 按图像的替代字符串对列进行排序

javascript - 谷歌关闭 : trouble type checking parameters that should be functions

module - 闭包编译器是否支持 CommonJS 风格的 require 和 js 文件?

javascript - 如何在 JsDoc 中记录具有多个参数顺序选项的函数?

javascript - RouteChangeStart 和 RouteChangeSuccess 事件在页面加载时不起作用

javascript - Android 从加载了 loadURL 的网页访问共享首选项

javascript - Google Closure 编译器发出警告 : incompatible types; even when parameters have common types, 有没有办法解决这个问题?

javascript - 如何在 JSDoc 中注释具有可变参数数量的 Function 类型的对象?