簡體   English   中英

Javascript 中的原型到 Typescript 語法

[英]Prototypes in Javascript to Typescript Syntax

有人知道如何將這段 Javascript 代碼寫入 Typescript 嗎? 特別是類里面的原型給我帶來了問題......

var Module = (function () {
    function Module(name) {
       this.name = name;
    }
    Module.prototype.toString = function () {
       return this.name;
    };
    return Module;
})();

var Student = (function () {
    function Student(name, studentNumber) {
         this.bookedModules = [];
         this.name = name;
         this.studentNumber = studentNumber;
}
Student.prototype.bookModule = function (bookedModule) {
      this.bookedModules.push(bookedModule);
};
Student.prototype.bookedModuleNames = function () {
      return this.bookedModules.map(function (module) {
            return module.toString();
      });
    };
    return Student;
})();

在打字稿中,您使用類,編譯器將為您完成原型工作。
您的代碼相當於:

class Module {
    public name: string;

    constructor(name: string) {
        this.name = name;
    }

    toString(): string {
        return this.name;
    }
}

class Student {
    public name: string;
    public studentNumber: number;
    public bookedModules: Module[];

    constructor(name: string, studentNumber: number) {
        this.name = name;
        this.bookedModules = [];
        this.studentNumber = studentNumber;
    }

    bookModule(book: Module): void {
        this.bookedModules.push(book);
    }

    bookedModuleNames(): string[] {
        return this.bookedModules.map(book => book.name);
    }
}

操場上的代碼

編譯成:

var Module = (function () {
    function Module(name) {
        this.name = name;
    }
    Module.prototype.toString = function () {
        return this.name;
    };
    return Module;
}());
var Student = (function () {
    function Student(name, studentNumber) {
        this.name = name;
        this.bookedModules = [];
        this.studentNumber = studentNumber;
    }
    Student.prototype.bookModule = function (book) {
        this.bookedModules.push(book);
    };
    Student.prototype.bookedModuleNames = function () {
        return this.bookedModules.map(function (book) { return book.name; });
    };
    return Student;
}());

使用類 - 打字稿將為您生成此代碼:

class Module {
    constructor(public name) {
    }

    toString() {
        return this.name;
    }
}

class Student {
    bookedModules: Module[];   

    constructor(public name, public studentNumber) {
        this.bookedModules = [];
    }

    bookModule(bookedModule: Module) {
        this.bookedModules.push(bookedModule);
    } 

    //...
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM