[英]How do you extend an abstract class in javascript and annotate for closure compiler but without closure library?
Say I have an abstract class 说我有一个抽象课
/**@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.
and i want to extend this class, normally, I would do something like 我想扩展此类,通常,我会做类似的事情
/**@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;
};
But closure compiler says 但是闭包编译器说
JSC_INSTANTIATE_ABSTRACT_CLASS: cannot instantiate abstract class
refering to the line Foo.prototype = new AbsFoo();
参考行
Foo.prototype = new AbsFoo();
So how would I do this in a way that would keep the prototype inheritance, and the ability to use instanceof
all the way up the class chain, but also make the compiler happy? 那么,我该如何保持原型的继承性以及在类链中始终使用
instanceof
的能力,同时又使编译器感到满意呢?
I use goog.inherits
in this situation. 在这种情况下,我使用
goog.inherits
。 Since you don't want to use closure library you could copy just goog.inherits
from closure-library/closure/goog/base.js . 由于您不想使用闭包库,因此可以仅从closure-library / closure / goog / base.js复制
goog.inherits
。 Maybe give it the name googInherits
. 也许给它起名字
googInherits
。 The code is then something like this: 代码如下所示:
/**@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.