简体   繁体   中英

Prototypes in Javascript to Typescript Syntax

Does somebody know how do I write this Javascript code into 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);
    } 

    //...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM