为什么我不能从同一类中的另一个方法调用此方法

Why can I not call this method from another method in the same class?

本文关键字:一类 另一个 方法 此方法 调用 不能 为什么      更新时间:2023-09-26

在下面的代码中,我不知道如何从handler(sock)方法内部调用parseData(data)方法。

我已经尝试了其他问题的所有方法:其他问题

"use strict";
var net = require('net');
var HOST = '127.0.0.1';
class Sorter {
    constructor(sorter) {
        this.sorter = sorter;
        console.log(sorter.name + ' Port: ' + sorter.port + ' running!');
        this.initialize();
    }
    initialize() {
        net.createServer(this.handler).listen(this.sorter.port, HOST);
    }
    handler(sock) {
        sock.on('data', function(data) {
            console.log('DATA ' + sock.remoteAddress + ':' + sock.localPort + ':   ' + data);
            parseData(data);
            // Write the data back to the socket, the client will receive it as data from the server
            //sock.write('Hello there'); //response
        });
        // Add a 'close' event handler to this instance of socket
        sock.on('close', function(data) {
            console.log('CLOSED: ' + sock.remoteAddress +' '+ sock.remotePort);
        });
    }
    parseData(data) {
        // find out if I have a carton with the data recvd
        console.log('looking for container: ' + data + ' ...');
        console.dir(this.findByContainer(data));
    }
    findByContainer(container) {
        return GLOBAL.CARTONS.filter(function( obj ) {
            return +obj.container === +container;
        })[0];
    }
}
module.exports = Sorter;

使用this.parseData(data);这个必须被引用,因为类instinciation。请参阅方法内部的其他调用。

parseData不在作用域中。当您从不同的作用域调用函数时,需要绑定函数,使它们处于作用域中。

当你打电话给this.initialize()时,你的想法是正确的;它不是全局函数,因此需要参考this。您需要对parseData执行同样的操作。

但是,因为您是从回调调用parseData,所以this将不是您所期望的。您需要绑定回调或在回调之外保存对this的引用。我更喜欢前者,但这取决于你。

使用bind:

sock.on('data', function(data) {
    console.log('DATA ' + sock.remoteAddress + ':' + sock.localPort + ':   ' + data);
    this.parseData(data);
    // Write the data back to the socket, the client will receive it as data from the server
    //sock.write('Hello there'); //response
}.bind(this));

使用保存的对this:的引用

var _this = this;
sock.on('data', function(data) {
    console.log('DATA ' + sock.remoteAddress + ':' + sock.localPort + ':   ' + data);
    _this.parseData(data);
    // Write the data back to the socket, the client will receive it as data from the server
    //sock.write('Hello there'); //response
});

您也可以为回调使用箭头函数。箭头函数的作用域是自动维护的,但仍需要引用this才能调用parseData

使用箭头功能:

sock.on('data', data => {
    console.log('DATA ' + sock.remoteAddress + ':' + sock.localPort + ':   ' + data);
    this.parseData(data);
    // Write the data back to the socket, the client will receive it as data from the server
    //sock.write('Hello there'); //response
});