2017-01-08 11 views
1

TypescriptにこのJavascriptコードを書く方法を知っていますか?特に、クラスの内部プロトタイプは私の問題...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

使用クラス原因 - typescriptですがあなたのためにこのコードを生成します。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); 
    } 

    //... 
} 
0

あなたはクラスを使用し、コンパイラが行いますプロトタイプはあなたのために働く。
あなたのコードは同等です:

にコンパイル
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

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; 
}()); 
関連する問題