我有许多艺术作品想放入数组中。每个作品都有属性,我试图用一个类来描述。我想用类创建类型并将数据推送到数组上。我不确定构造函数在做什么?我认为它应该提供一种创建类的新实例的方法?Typescript在类中创建数组,然后推到数组上
我的TS的代码如下:
class Artwork {
private _artTitle: string;
private _slideUrl: string;
private _artPrice: string;
private _artMedium: string;
private _artDimensions: string;
private _artDesc: string;
constructor(
artTitle: string,
slideUrl: string,
artPrice: string,
artMedium: string,
artDimensions: string,
artDesc: string
){
this._artTitle = artTitle;
this._slideUrl = slideUrl;
this._artPrice = artPrice;
this._artMedium = artMedium;
this._artDimensions = artDimensions;
this._artDesc = artDesc;
}
}
let Artwks: string [];
Artwks.push(new Artwork());
Artwks[0].slideUrl = './assets/SBI_Slide_1.jpg';
Artwks[0].artTitle = "'Surprising Breakfast Ideas'";
Artwks[0].artPrice = "£400";
Artwks[0].artMedium = "Acrylic on canvas";
Artwks[0].artDimensions = '7" x 12"';
Artwks[0].artDesc = '...Inspired by trailing clauses and footling concerns, this latest injunction into the darkened forest of prevarication yields a miasma of plethoras, tantalising us with a fleeting array of nuances...';
console.log(Artwks);
仅供参考,你可以在构造函数中定义的东西作为'private/protected/public',然后访问它而不必单独声明类变量,然后从构造函数中为它们赋值。例如。 '构造函数(private _artTitle:string)' – JBC