2016-08-13 90 views
1

我創建的非常簡單的模塊用於測試此嘗試的可行性。這裏是SPServerApp.ts開頭:如何使用Typescript創建node.js模塊

class SPServerApp { 
    public AllUsersDict: any; 
    public AllRoomsDict: any; 
    constructor() { 
     this.AllUsersDict = {}; 
     this.AllRoomsDict = {}; 
    } 
} 
module.exports = SPServerApp(); 
在我的應用程序

然後,我有這樣的要求聲明:

var serverapp = require('./SPServerApp'); 

然後我嘗試訪問其中的一個詞典,像這樣:

serverapp.AllUsersDict.hasOwnProperty(nickname) 

但是得到錯誤:

TypeError: Cannot read property 'hasOwnProperty' of undefined

任何人都可以看到我在這裏做錯了嗎?

謝謝,E.

+0

您還沒有實例化類。添加'新'或創建一個新的實例,你需要它。 – Phix

+1

確實有效。謝謝Phix。 –

+1

我認爲這個鏈接會幫助你。 http://stackoverflow.com/questions/23739044/how-do-you-write-a-node-module-using-typescript –

回答

2

問題是你在調用構造函數時忘了'new'關鍵字。該行應爲:

module.exports = new SPServerApp(); 

如果不使用您的構造函數將被視爲正常功能,將剛剛返回undefined(因爲你沒有明確地返回任何東西)。另外'this'不會指向你在構造函數中所期望的。

省略新的在Node中實際上很常見。但是,對於這個工作,你必須明確地防範稀少調用構造函數,像這樣:

constructor() { 
    if (! (this instanceof SPServerApp)) { 
     return new SPServerApp(); 
    } 
    this.AllUsersDict = {}; 
    this.AllRoomsDict = {}; 
} 

順便說一句,在打字稿你也可以使用模塊的語法。 TS編譯器會將其轉換爲export/require語句。隨着ES6風格模塊的例子是這樣的:

export class SPServerApp { 
    public AllUsersDict: any; 
    public AllRoomsDict: any; 
    constructor() { 
     this.AllUsersDict = {}; 
     this.AllRoomsDict = {}; 
    } 
} 
export var serverapp = new SPServerApp(); 

在你的其他TS文件你剛纔導入:

import { serverapp } from './SPServerApp'; 

serverapp.AllUsersDict.hasOwnProperty('something');