简体   繁体   English

Javascript 中的原型到 Typescript 语法

[英]Prototypes in Javascript to Typescript Syntax

Does somebody know how do I write this Javascript code into Typescript?有人知道如何将这段 Javascript 代码写入 Typescript 吗? Especially the prototype inside of the class causes me problems...特别是类里面的原型给我带来了问题......

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;
})();

In typescript you use classes, the compiler will do the prototype work for you.在打字稿中,您使用类,编译器将为您完成原型工作。
You code is equivalent to:您的代码相当于:

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);
    }
}

( code in playground ) 操场上的代码

Which compiles into:编译成:

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;
}());

Use classes - typescript will generate this code for you:使用类 - 打字稿将为您生成此代码:

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