节点JS变量范围

时间:2012-12-06 15:31:49

标签: node.js variables scope

我有下一段代码

function Server() {

    function eventHandler(data) {
        console.log('DATA ' + this.server.socket.remoteAddress + ': ' + data);
        socket.write('You said "' + data + '"');
    }

    function connectionHandler(socket) {
        console.log('server connected');
        console.log('CONNECTED: ' + socket.remoteAddress +':'+ socket.remotePort);
        socket.on('data', eventHandler);
    }

    this.server = net.createServer(connectionHandler);

    this.port = undefined;

    this.startServer = function(port) { //Maybe change backlog for security reasons
        this.port = port;
        this.server.listen(port, function() { //'listening' listener add handle object here
            console.log('server bound');});
    }
}

每次建立连接我都会

server bound
server connected
CONNECTED: 132.65.16.64:55028

/a/fr-05/vol/netforce/stud/yotamoo/ex4/myHTTP.js:7
        console.log('DATA ' + this.server.socket.remoteAddress + ': ' + data);
                                          ^
TypeError: Cannot read property 'remoteAddress' of undefined
    at Socket.eventHandler (/a/fr-05/vol/netforce/stud/yotamoo/ex4/myHTTP.js:7:43)
    at Socket.emit (events.js:67:17)
    at TCP.onread (net.js:329:14)

这当然与evenHandler()有关。我不明白如何在Node JS及其范围中创建对象。例如,socketdata在哪里创建?它们的范围是什么?

非常感谢

2 个答案:

答案 0 :(得分:0)

这意味着当前的呼叫功能。

在您的情况下,这指的是eventHandler,而eventHandler只将数据作为可访问的值。

如果您尝试访问套接字,您将收到类似的异常。因为套接字不在该函数范围内。

套接字和数据都来自异步回调,这是node.js的主要模式。

答案 1 :(得分:0)

您必须bind this您希望事件处理函数使用的function Server() { function eventHandler(data) { console.log('DATA ' + this.server.socket.remoteAddress + ': ' + data); socket.write('You said "' + data + '"'); } function connectionHandler(socket) { console.log('server connected'); console.log('CONNECTED: ' + socket.remoteAddress +':'+ socket.remotePort); socket.on('data', eventHandler.bind(this)); } this.server = net.createServer(connectionHandler.bind(this)); this.port = undefined; this.startServer = function(port) { this.port = port; this.server.listen(port, function() { console.log('server bound');}); }; } 值,如下所示:

{{1}}