繁体   English   中英

如何在javascript中扩展抽象类并为闭包编译器添加注释,但没有闭包库?

[英]How do you extend an abstract class in javascript and annotate for closure compiler but without closure library?

说我有一个抽象课

/**@constructor
 * @abstract*/
function AbsFoo(){}

/**@return {number}
 * @param {number} a
 * @param {number} b */
AbsFoo.prototype.aPlusB = function(a,b){
    return a + b
};

/**@abstract
 * @return {number}
 * @param {number} c
 * @param {number} d */
AbsFoo.prototype.cMinusD = function(c,d){}; //extending class need to implement.

我想扩展此类,通常,我会做类似的事情

/**@constructor
 * @extends {AbsFoo} */
function Foo(){
    AbsFoo.apply(this);
}

Foo.prototype = new AbsFoo();
Foo.prototype.constructor = Foo;

Foo.prototype.doSomething = function(c,d){
    return c - d;
};

但是闭包编译器说

JSC_INSTANTIATE_ABSTRACT_CLASS: cannot instantiate abstract class

参考行Foo.prototype = new AbsFoo();

那么,我该如何保持原型的继承性以及在类链中始终使用instanceof的能力,同时又使编译器感到满意呢?

在这种情况下,我使用goog.inherits 由于您不想使用闭包库,因此可以仅从closure-library / closure / goog / base.js复制goog.inherits 也许给它起名字googInherits 代码如下所示:

/**@constructor
 * @extends {AbsFoo}
 */
Foo = function(){
    AbsFoo.apply(this);
}
googInherits(Foo, AbsFoo);

/** @inheritDoc */
Foo.prototype.cMinusD = function(c,d){
    return c - d;
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM