2017-08-25 59 views
0

我有许多艺术作品想放入数组中。每个作品都有属性,我试图用一个类来描述。我想用类创建类型并将数据推送到数组上。我不确定构造函数在做什么?我认为它应该提供一种创建类的新实例的方法?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); 
+1

仅供参考,你可以在构造函数中定义的东西作为'private/protected/public',然后访问它而不必单独声明类变量,然后从构造函数中为它们赋值。例如。 '构造函数(private _artTitle:string)' – JBC

回答

0

需要声明的变量,并调用像这样的类的构造函数:

let Artwks: Artwork []=[]; 

    Artwks.push(new Artwork("'Surprising Breakfast Ideas'", '', '', '', '', '')); 

但是,如果你的类只有数据,我会建议使得它的界面和使用JSON文本创建数组元素:

interface Artwork { 

    artTitle: string; 
    slideUrl?: string; //optional memeber 
    artPrice: string; 
    artMedium?: string; 
    artDimensions?: string; 
    artDesc?: string 
} 

let Artwks: Artwork []=[]; 

Artwks.push({ 
    artTitle: '', 
    artPrice: '', 
    artDesc: '', 
    artDimensions:'' 
}); 

这个版本是一个很大的可读性,并且可以更容易maskes一些成员可选

+0

好的界面选项是我想要的,但是你的代码不适合我 - 我错过了什么? – Davtho1983

+0

你有什么错误? –

+0

此代码不起作用,因为您没有初始化变量 –

0

你也可以传递参数的构造函数来创建与性能的新实例指定如下:

您也需要前发起新的空数组您将Artwork对象推送到它。

let Artwks:Array<Artwork>=[]; 

let artwk = new Artwork("'Surprising Breakfast Ideas'",'./assets/SBI_Slide_1.jpg', "£400", "Acrylic on canvas", '7" x 12"', '...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...'); 

Artwks.push(artwk); 

console.log(Artwks); 
1

下面的代码应该工作:

let artworks: Artwks[] = []; 

artworks.push(new Artwork(
"'Surprising Breakfast Ideas'", 
'./assets/SBI_Slide_1.jpg', 
"£400", 
"Acrylic on canvas", 
'7" x 12"', 
    '...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...'; 
)); 

您必须填写所有参数的构造函数来创建类的新实例