扩展对象并将其分配给其父对象

时间:2017-06-28 12:38:07

标签: typescript

我不确定标题听起来是否正确。如果需要修改,请建议。

我有一个名为programme

的对象
export class Programme {
    id: string;
    imageUrl: string;
    title: string;
    price: number;
    subject: string;
    level: string;
    tutorId: string;
    click: number;

    constructor(level?: string) {
        this.click = 0;
        this.level = level ? level : "";
    }
}

我有另一个对象ProgrammeWrapper

export class ProgrammeWrapper extends Programme{
    lesson: Lesson[];
    tutor: User;

    constructor(prog: Programme){
        super();
    }
}

现在问题就出现了:

var programme = new Programme();//this is coming from database
var user = new User();
var lessons = new Lesson[];
var programmeWrap = new ProgrammeWrapper();
programmeWrap.tutor = user;
programmeWrap.lessons = lessons;

我如何分配程序? programmeWrapper?

1 个答案:

答案 0 :(得分:1)

编写代码的方式ProgrammeWrapper是一个程序,不需要创建不同的程序实例。

ProgrammeWrapper也是一个程序,程序的所有属性也可以在ProgrammeWrapper上获得。

ProgrammeWrapper可以这样写:

export class ProgrammeWrapper extends Programme{
        lesson: Lesson[];
        tutor: User;

        constructor(level? : string){
            super(level);
        }
    }

可以像这样使用:

var user = new User();
var lessons = new Lesson[];
var programmeWrap = new ProgrammeWrapper();
programmeWrap.tutor = user;
programmeWrap.lessons = lessons;
programmeWrap.id = '5'; // Programme property is available

如果您只想拥有一个具有该界面的对象并访问它,您可以这样做:

interface Programme {
    id: string;
    imageUrl: string;
    title: string;
    price: number;
    subject: string;
    level: string;
    tutorId: string;
    click: number;
}

class ProgrammeWrapper {
    lesson: string[];
    tutor: string;
    constructor(public prog: Programme) {
    }
}

let programme: Programme = null; // comes from somewhere else
let programmeWrapper = new ProgrammeWrapper(programme);

console.log(programmeWrapper.prog.id);