2011-11-18 25 views
0

,我有以下的CoffeeScript代碼示例:獲得一流水平的變量http.createServer requestListener

class TestClass 
    constructor:() -> 
     @list = new Object() 

    addToList: (key, value) -> 
     @list[key] = value 

    printList:() -> 
     console.log("This is printed from printList:", @list) 

    startHttp:() -> 
     http = require("http") 
     http.createServer(@printList).listen(8080) 

test = new TestClass() 
test.addToList("key", "value") 
test.printList() 
test.startHttp() 

當我運行的代碼,並進行HTTP請求到127.0.0.1:8080,我期望能獲得下面的輸出:

這是從印刷的printList:{鍵: '值'}
這是從印刷的printList:{鍵: '值'}

但我得到的,而不是以下:

這是從的printList印刷:{鍵: '值'}
這是從的printList印刷:未定義

爲什麼它printList功能從HTTP服務器調用時,不能訪問list變量嗎?

我正在使用Node.js v0.6.1和CoffeeScript v1.1.3。

回答

2
printList:() => 
    console.log("This is printed from printList:", @list) 

使用=>this值,因此「作品」,你希望綁定功能。

聲明:實例可能會中斷。咖啡是所有我關心的黑魔法。

你真正想要做的是調用的方法正確的對象

that = this 
http.createServer(-> 
    that.printList() 
).listen 8080 

上或普通的JavaScript。

var that = this; 
http.createServer(function() { 
    that.printList(); 
}).listen(8080); 
+0

謝謝,我對JavaScript的面向對象編程非常陌生,但是這幫了我很大的忙。 –