有人知道如何将这个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;
})();
答案 0 :(得分:2)
在打字稿中你使用类,编译器会为你做原型工作 您的代码相当于:
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;
}());
答案 1 :(得分:0)
使用类 - typescript将为您生成此代码:
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);
}
//...
}