未初始化Typescript类属性
我有以下课程:未初始化Typescript类属性,typescript,Typescript,我有以下课程: export abstract class LayerStyle { protected configuration: { [key: string]: string }; protected style: ol.style.Style[]; constructor(config: { [key: string]: string }) { this.configuration = config; this.createSt
export abstract class LayerStyle {
protected configuration: { [key: string]: string };
protected style: ol.style.Style[];
constructor(config: { [key: string]: string }) {
this.configuration = config;
this.createStyle();
}
protected abstract createStyle(): void;
getStyle() {
return this.style;
}
}
及其子类:
import { LayerStyle } from './LayerStyle';
export class PointStyle extends LayerStyle {
//default values
FILL_COLOR = 'rgba(255,255,255,0.4)';
STROKE_COLOR = '#3399CC';
STROKE_WIDTH = 1.25;
RADIUS = 5;
createStyle() {
let fillColor = this.FILL_COLOR;
let strokeColor = this.STROKE_COLOR;
let strokeWidth = this.STROKE_WIDTH;
let radius = this.RADIUS;
...
}
}
当我创建一个新的PointStyle
let style=new PointStyle(styles).getStyle()代码>表示所有类变量(this.FILL\u COLOR
,this.STROKE\u COLOR
,this.STROKE\u WIDTH
,this.RADIUS
)在createStyle()
内均为空。为什么?它不应该用它的属性创建类吗?我是否应该在子构造函数中初始化它们,然后用super()
调用父构造函数?问题在于执行顺序。字段初始值设定项只是构造函数中指定字段的语法糖,但构造函数中执行的第一条语句是基构造函数。如果我们查看生成的代码,问题就会变得更清楚:
var PointStyle = /** @class */ (function (_super) {
__extends(PointStyle, _super);
function PointStyle() {
// Super executed here !
var _this = _super !== null && _super.apply(this, arguments) || this;
//Field initialization here after createStyle is executed!
_this.FILL_COLOR = 'rgba(255,255,255,0.4)';
_this.STROKE_COLOR = '#3399CC';
_this.STROKE_WIDTH = 1.25;
_this.RADIUS = 5;
return _this;
}
...
return PointStyle;
}(LayerStyle));
exports.PointStyle = P
调用应该在构造函数中覆盖的成员通常是一个坏主意,正是因为这种问题,您应该在派生类型中调用createStyle
,或者添加一个参数来抑制执行从派生类调用的createStyle
:
export abstract class LayerStyle {
protected configuration: { [key: string]: string };
protected style: ol.style.Style[];
constructor(config: { [key: string]: string }, callInit: boolean = true) {
this.configuration = config;
if(!callInit) this.createStyle();
}
protected abstract createStyle(): void;
getStyle() {
return this.style;
}
}
export class PointStyle extends LayerStyle {
constructor(config: { [key: string]: string }, callInit: boolean = true) {
super(config, false);
if(callInit) this.createStyle();
}
//default values
FILL_COLOR = 'rgba(255,255,255,0.4)';
STROKE_COLOR = '#3399CC';
STROKE_WIDTH = 1.25;
RADIUS = 5;
createStyle() {
let fillColor = this.FILL_COLOR;
let strokeColor = this.STROKE_COLOR;
let strokeWidth = this.STROKE_WIDTH;
let radius = this.RADIUS;
}
}
可以添加整个子类代码吗?构造函数不在那里,必须是oneHmmm。我认为它可以隐式地扩展构造函数。谢谢你的解释。这就是我想要的:)有了它,我可以适当地改变课程。