我的代码开始有很多嵌套,并且它开始难以维护。我试图将回调函数声明为非任意函数,并将它们作为参数传递。
我要做的就是转换此代码:
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
变量?
如果我需要修改它怎么办?
答案 0 :(得分:1)
您可以使用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)); // <--
});