在http.createServer requestListener中获取类级变量

时间:2011-11-18 16:14:27

标签: node.js coffeescript

我有以下CoffeeScript代码示例:

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()

当我运行代码并向127.0.0.1:8080发出HTTP请求时,我希望得到以下输出:

  

这是从printList打印的:{key:'value'}
  这是从printList打印的:{key:'value'}

但我得到以下内容:

  

这是从printList打印的:{key:'value'}
  这是从printList打印的:undefined

为什么printList函数在从HTTP服务器调用时无法访问list变量?

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

1 个答案:

答案 0 :(得分:2)

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

使用=>this的值绑定到该函数,使其“正常”工作。

免责声明:实例可能会中断。 Coffeescript对我所关心的一切都是黑魔法。

您真正想要做的是在正确的对象上调用方法

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

或者是普通的javascript。

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