gpt4 book ai didi

typescript 类属性未被初始化

转载 作者:搜寻专家 更新时间:2023-10-30 21:48:43 30 4
gpt4 key购买 nike

我有以下类(class):

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_COLOR, this.STROKE_COLOR,this.STROKE_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;
}
}

关于 typescript 类属性未被初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49856423/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com