我在 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/