2011-11-18 59 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的面向对象编程非常陌生,但是这帮了我很大的忙。 –