首页 文章

实例化Typescript类时出错(错误不是构造函数)

提问于
浏览
0

我是TypeScript的新手,并且在基本类实例化方面遇到了麻烦 .

我有一个命名空间RecordsService,其中声明了类Record . 我希望能够在RecordsService中创建记录,然后通过其他方法等公共方法访问它们 .

export namespace RecordsService {

    let records: Array<Record> = new Array();

    function init () {
        let record1 = new Record(new Date(), 1);
    }
    init();

    export function getAllRecords() {
        return records;
    }

    class Record {

        constructor (public date: Date, public id: number) {
            this.date = date;
            this.id = id;
        }
    }
}

上面没有抛出任何转换错误,但在运行时我得到一个控制台错误与下面

TypeError:Record不是构造函数(...)

错误的行 let record1 = new Record(new Date(), 1); 在这种情况下如何创建新记录?

Plunker,查看控制台日志以查看错误:https://plnkr.co/edit/FNk8b1ZwA5HL3I7wAnTq?p=preview

1 回答

  • 1

    您需要将 Record 类移到 init 函数之上:

    class Record {
        constructor (public date: Date, public id: number) {
            this.date = date;
            this.id = id;
        }
    }
    
    let records: Array<Record> = new Array();
    
    function init () {
        let record1 = new Record(new Date(), 1);
    }
    init();
    

    或者在 Record 定义后调用 init 函数:

    let records: Array<Record> = new Array();
    
    function init () {
        let record1 = new Record(new Date(), 1);
    }
    
    export function getAllRecords() {
        return records;
    }
    
    class Record {
        constructor (public date: Date, public id: number) {
            this.date = date;
            this.id = id;
        }
    }
    
    init();
    

    发生这种情况的原因是javascript是一种解释型语言,解释器在另一种语言之后解析代码行,因此它在解释 Record 类之前到达 init() 部分(在原始代码中) .

    init 函数的内容在类定义之前是安全的,之后只需执行它 .

    另外,如果你这样做:

    constructor (public date: Date, public id: number)
    

    然后没有必要这样做:

    this.date = date;
    this.id = id;
    

    它是:

    class Record {
        constructor (public date: Date, public id: number) {}
    }
    

    要么

    class Record {
        public date: Date;
        public id: number;
    
        constructor (date: Date, id: number) {
            this.date = date;
            this.id = id;
        }
    }
    

相关问题