1

httpでサーバーを書いていますnode.jsServerオブジェクトには、要求に応じてクライアントに送信する必要があるいくつかのフィールドがあります。status()これが、に渡す必要がある理由router.route()です。つまり、(リクエストが解析された後に) 内部から呼び出して、更新変数値を返すことができます。問題は、status()が呼び出されたときに、フィールド値ではなくオブジェクト リテラルが出力されることです。

コンストラクタServerは次のとおりです。

this.server = net.createServer(connectionHandler);  
    this.resourceMap = resourceMap;
    this.rootFolder = rootFolder;
    this.isStarted = false;
    this.startedDate = undefined;
    this.port = undefined;
    this.numOfCurrentRequests = 0;

function status() {
    return {
        "isStarted" : this.isStarted,
        "startedDate" : this.startedDate,
        "port" : this.port,
        "resourceMap" : this.resourceMap,
    };
}

function connectionHandler(socket) {
    console.log('server connected');
    console.log('CONNECTED: ' + socket.remoteAddress +':'+ socket.remotePort);
    socket.setEncoding('utf8');
    socket.on('data',function(data) {
            this.numOfCurrentRequests += 1;
            router.route(status,data,socket,handle,resourceMap,rootFolder);
            });
}

this.startServer = function(port) {
    this.port = port;
    this.isStarted = true;
    this.startedDate = new Date().toString();
    this.server.listen(port, function() {
            console.log('Server bound');
        });
}
}

そして、ステータスが内部から呼び出されるrouter.route()と、

function status() {
        return {
            "isStarted" : this.isStarted,
            "startedDate" : this.startedDate,
            "port" : this.port,
            "resourceMap" : this.resourceMap,
        };
    }

私が理解しているように、関数は変数であるため、値で渡されます。私の問題を解決する方法はありますか?

ありがとう

4

2 に答える 2

0

Google検索で実際に「関数ポインタ」を意味していた私のような人のために、ここに答えがあります:

app.js ファイルに外部ファイルが必要であることを認めます。

var _commandLineInterface("./lib/CommandLine")();
var _httpServer = require("./lib/HttpServer")(_commandLineInterface);

次に、HttpServer.js ファイルで、_httpServer コンストラクターの引数として渡された _commandLineInterface オブジェクトを使用することを認めます。我々はする :

function HttpServer(_cli){
    console.log(_cli);
}

module.exports = HttpServer;

BZZZZZZZZT!エラー。_cli ポインターが未定義のようです。終わりました。すべてが失われます。

わかりました... ここに秘訣があります: CommandLine オブジェクトを覚えていますか?

function CommandLine(){
    ...

    return this;
}

module.exports = CommandLine;

うん。nodejs の動作に慣れていない場合、これはかなり奇妙です。

オブジェクトに対して、作成後に元に戻さなければならないことを伝える必要があります。Javascript の動作をフロントエンドで処理することに慣れている人にとって、それは普通のことではありません。

したがって、小さな「リターン トリック」を追加すると、他のオブジェクト内からポインタを取得できるようになります。

function HttpServer(_cli){
    console.log(_cli); // show -> {Object}
}

私のようなnodejsの初心者に役立つことを願っています。

于 2014-03-23T10:29:49.827 に答える
0

私が明らかにあなたに連絡した場合、関数ポインターは必要ありませんが、それは結果です。したがってstatus、次のように渡す必要があります。

router.route(status(),data,socket,handle,resourceMap,rootFolder);

最終的に、次のオブジェクトが渡されます。

return {
        "isStarted" : this.isStarted,
        "startedDate" : this.startedDate,
        "port" : this.port,
        "resourceMap" : this.resourceMap,
    }

それらを表示したいので、コールバックで次のコードを使用します

for(var s in status) {
    console.log(s+" : "+status[s]);
}
于 2012-12-11T11:21:24.850 に答える