[英]Google closure compiler: How to do inheritance when using a factory
Say I have a class Car. 假设我有一辆汽车。
/**
*
* @constructor
* @extends {Component}
*/
obj.Car = function(prop1, prop2) {
goog.base(this, prop1);
this.prop2 = prop2;
};
goog.inherits(obj.Car, Component);
/**
*
* @return {obj.Car}
*/
obj.Car.create = function(a,b,c) {
var prop1 = obj.Car.createProp1(a,b,c);
var prop2 = obj.Car.createProp2(a,b,c);
return new obj.Car(prop1, prop2);
}
Cool. 凉。 Now I want to sublcass car.
现在我要租车。 Call it SuperCar.
称之为超级跑车。
obj.SuperCar = function(prop1,prop2) {
goog.base(this, prop1, prop2);
};
goog.inherits(obj.SuperCar, obj.Car);
How do I write the factory create method for SuperCar so that another class can also extend SuperCar? 如何编写SuperCar的工厂创建方法,以便另一个类也可以扩展SuperCar?
So, ideally: 因此,理想情况下:
/**
* @return {obj.SuperCar}
*/
obj.SuperCar.create() = function() {
return /** type {obj.SuperCar} */ Obj.Car.create.apply(this, arguments);
};
However, this means I have to change obj.Car to: 但是,这意味着我必须将obj.Car更改为:
/**
* @this {*) ????????? only this works
* @return {obj.Car}
*/
obj.Car.create = function(a,b,c) {
var prop1 = obj.Car.createProp1(a,b,c);
var prop2 = obj.Car.createProp2(a,b,c);
return new this(prop1, prop2);
};
This Javascript actually runs uncompiled and compiles. 该Javascript实际上未经编译就可以运行。 But I get a TypeError when running it compiled.
但是运行编译时出现TypeError。 Does anyone know the best solution for this?
有谁知道最好的解决方案吗? I've tried a few thing but can't seem to get it right.
我尝试了几件事,但似乎无法正确解决。
I will assume that this is the base class. 我将假定这是基类。
SuperCar.js SuperCar.js
/**
* @constructor
*/
obj.SuperCar = function() {
};
/**
* @return {obj.SuperCar}
*/
obj.SuperCar.create = function() {
return new obj.SuperCar();
}
Car.js Car.js
/**
* @param {*} prop1
* @constructor
* @extends {obj.SuperCar}
*/
obj.Car = function(prop1) {
goog.base(this);
this.prop1 = prop1;
};
goog.inherits(obj.Car, obj.SuperCar);
/**
* @param {*} prop1
* @return {obj.Car}
* @override
*/
obj.SuperCar.create = function(prop1) {
return new obj.Car(prop1);
}
Normally if you are going to override a function you can use /** @inheritDoc */
annotation or if you are going to change the function definition then write the new function definition and add the @override
annotation. 通常,如果要覆盖功能,则可以使用
/** @inheritDoc */
批注,或者如果要更改功能定义,则编写新的函数定义并添加@override
批注。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.