如何与匿名函数通信

how can I communicate with an anonymous function

本文关键字:函数 通信      更新时间:2023-09-26

我的代码开始有很多嵌套,而且开始很难维护。我试图将回调函数声明为非anymous函数,并将其作为参数传递。

我所要做的就是转换这个代码:

    http.createServer(function(clientReq,clientRes){
        var clientRequestHeaders=clientReq.headers;
        //example.com would give me a url that I need to send a GET request
        http.request({hostname:'example.com'}, function(res){
            var data='';
            res.on('data', function(chunk)){
                data+=chunk;
            });
            res.on('end',function(){
                http.request({hostname:data, headers: clientRequestHeaders}, function(res){});
            });
        });
    });//end createServer

到此:

    function func(res){
            var data='';
            res.on('data', function(chunk){
                data+=chunk;
            });
            res.on('end',function(){
                http.request({hostname:data, headers: clientRequestHeaders}, function(res){});
                                                     //^^^^ can't access headers now
            });
    }
    http.createServer(function(clientReq,clientRes){
        var clientRequestHeaders=clientReq.headers;
        //example.com would give me a url that I need to send a GET request
        http.request({hostname:'example.com'}, func);
    });//end createServer

所以我的问题是:如何传递clientRequestHeaders变量?

如果我也需要修改它呢?

您可以使用Function.prototype.bind

function callback(headers, res) {
  // ... your original anonymous function
}
http.createServer(function(clientReq,clientRes){
  var clientRequestHeaders = clientReq.headers;
  http.request({hostname:'example.com'}, callback.bind(null, clientRequestHeaders)); // <--
});

或动态功能

function getCallback(headers)
  return function callback(res) {
    // ... your original anonymous function
  }
}
http.createServer(function(clientReq,clientRes){
  var clientRequestHeaders = clientReq.headers;
  http.request({hostname:'example.com'}, getCallback(clientRequestHeaders)); // <--
});