简体   繁体   中英

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();

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?

I use goog.inherits in this situation. Since you don't want to use closure library you could copy just goog.inherits from closure-library/closure/goog/base.js . Maybe give it the name 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;
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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