如何与匿名函数通信
how can I communicate with an anonymous function
我的代码开始有很多嵌套,而且开始很难维护。我试图将回调函数声明为非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)); // <--
});
相关文章:
- 创建一个类似链接的按钮,并通过Javascript函数打开一个新的弹出窗口
- 将函数的上下文应用于javascript变量
- 如何在JavaScript中将字符串转换为函数引用
- 用嵌套函数和默认函数定义函数
- 使用 jQuery 的 .on 函数如何获取事件的原始元素
- 无法导出函数expressjs/requestjs中的变量
- 函数参数中的数据与指定变量之间的任何性能差异
- JQuery合并了keyup和focusout两个函数
- ES6构造函数返回基类的实例
- 监视函数从服务返回不起作用,但作用域函数起作用
- 我可以在json对象中添加一个函数吗
- AngularJS:我可以跳过函数参数回调吗
- 如何使jQuery插件函数可调用以供独立使用,而不在集合上操作
- JavaScript数组排序(函数)用于对表行进行排序,而不是排序
- jquery点击函数select&取消选择
- 拨打'父亲'函数形式a'儿童'ReactJS中的组件
- Node.js v6.2.0类扩展不是函数错误
- 比较从函数和生成的日期对象
- 从内部指令与主指令的通信 - 调用函数
- 如何与匿名函数通信