【问题标题】:Pass function reference to function fails将函数引用传递给函数失败
【发布时间】:2016-02-16 04:49:52
【问题描述】:

我目前正在使用coffeescript 和使用nodejs 的websockets。
我创建了一个class SocketHandler 来管理 websocket 客户端:

class SocketHandler
    constructor: (@server) ->
        @server.on "connection", @onClientConnect   

    onClientConnect: (socket) ->
        console.log "client connected"
        socket.on "close", @onClientDisconnect

    onClientDisconnect: (code, message) ->
        console.log "client disconnected"

ws = require "ws"
server = ws.Server { port: 8080 }
sockethandler = new SocketHandler server

当我运行脚本并且客户端连接时,我收到以下错误消息:

client connected
events.js:210
    throw new TypeError('listener must be a function');
    ^

TypeError: listener must be a function
[...]

我不知道为什么会这样。在我看来,我将函数引用作为第二个参数传递给 socket.on

我试图进一步调查并尝试输出onClientDisconnect 以查看它的类型。
所以我改变了

onClientConnect: (socket) ->
    console.log "client connected"
    socket.on "close", @onClientDisconnect

onClientConnect: (socket) ->
    console.log "client connected"
    console.log @onClientDisconnect
    socket.on "close", @onClientDisconnect

导致获得 undefined 值作为输出。

现在我真的很困惑,我认为我错过了该语言如何工作的一些基本知识。
有谁能帮帮我吗?

【问题讨论】:

  • 那是你真正的缩进吗?不应该将onClientConnectonClientDisconnect 缩进一个级别,以便它们成为SocketHandler 的一部分吗?
  • @muistooshort:哦错过了。感谢您的提示,已更正。

标签: javascript node.js coffeescript


【解决方案1】:

提醒:@onClientConnectthis.onClientConnect 的简写。 this 正是这里的问题。函数调用的上下文(this 在函数内部)在 Javascript 中的调用时确定。当你传递一个函数时,接收者“没有上下文”接收它,当这样调用时,this 不会引用你正在考虑/想要/期望的 this

长话短说:您需要将this 绑定到您的函数,所以@onClientDisconnect 中的@ 实际上是指您的类实例:

@server.on "connection", @onClientConnect.bind @

CoffeeScript 中的替代方案(使用上下文绑定的粗箭头回调):

@server.on "connection", => @onClientConnect()

另见How to access the correct `this` context inside a callback?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-21
    • 1970-01-01
    • 1970-01-01
    • 2015-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多