使用闭包编译器正确键入实例变量

时间:2013-08-24 23:29:32

标签: javascript google-closure-compiler google-closure

我无法正确输入以下代码:

/**                                                                                                                                                                                      
 * @constructor                                                                                                                                                                          
 */
function F() {
      this.a = 0;
};

/**                                                                                                                                                                                      
 * @type {function(number)}                                                                                                                                                              
 */
F.prototype.g = function(b) {
    this.a += b;
};

我收到以下警告:

test.js:12: WARNING - could not determine the type of this expression
    this.a += b;
    ^

如何在此示例中正确键入this

- 编辑 -

如果您想查看警告,则需要按照here的说明将reportUnknownTypes设置为true。我试图获得100%类型的代码,我想我无法达到那个简单的程序。

2 个答案:

答案 0 :(得分:2)

/** @type {function(number)} */ 

未指定“this”类型,因此未知。要以这种方式指定它,您可以使用:

/** @type {function(this:F, number)}

使用“@param {number}”可让编译器从F原型上声明的事实推断出“this”类型。

答案 1 :(得分:1)

您似乎需要使用 @param {number} b 而不是 @type {function(number)} 。使用@param键入不会发出警告。没有多大意义,但它确实有效:

/**                                                                                                                                                                                      
 * @param {number} b                                                                                                                                                             
 */
F.prototype.g = function(b) {
    this.a += b;
};

-

原始答案:

我认为这是因为您没有在构造函数中键入a。试试这个:

/**                                                                                                                                                                                      
 * @constructor                                                                                                                                                                          
 */
function F() {

    /**
     * @type {number}
     * @private
     */
    this.a = 0;
};