【问题标题】:Getting class level variables in a http.createServer requestListener在 http.createServer requestListener 中获取类级别变量
【发布时间】:2011-11-19 00:31:15
【问题描述】:

我有以下 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。

【问题讨论】:

    标签: node.js coffeescript


    【解决方案1】:
    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);
    

    【讨论】:

    • 谢谢,我对 JavaScript 中的面向对象编程还很陌生,但这帮助了我。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多