javascript - 有人可以解释一下 howtonode 中的函数包装习惯吗?

标签 javascript node.js closures node.js-connect

我最近开始使用 Node.js、express 和 mongodb。由于express使用connect来提供中间件支持,所以我开始阅读中间件和connect。

我在 howtonode.org 上遇到了以下示例:

return function logItHandle(req, res, next) {
 var writeHead = res.writeHead; // Store the original function

 counter++;

 // Log the incoming request
 console.log("Request " + counter + " " + req.method + " " + req.url);

 // Wrap writeHead to hook into the exit path through the layers.
 res.writeHead = function (code, headers) {
   res.writeHead = writeHead; // Put the original back

   // Log the outgoing response
   console.log("Response " + counter + " " + code + " " + JSON.stringify(headers));

   res.writeHead(code, headers); // Call the original
 };

 // Pass through to the next layer
 next(); 
};

有人可以向我解释一下这个关闭中发生了什么吗?作者称其为

wrapping idiom to hook into the call to writeHead

这是什么意思?

最佳答案

它拦截对 res.writeHead 的调用,添加一些日志记录,然后将调用委托(delegate)给原始 res.writeHead

这就像 AOP 方法拦截的 super 简单。

关于javascript - 有人可以解释一下 howtonode 中的函数包装习惯吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15304437/

相关文章:

javascript - 在 google chrome 扩展中解析并显示特定网站或博客的 xml feed!

javascript - 从同一命名空间内通过其完全限定名称调用命名空间函数

javascript - 脚本产生我找不到的错误

node.js - NodeJs如何创建非阻塞计算

javascript - 创建具有 onClick 效果的幻灯片。在 Fiddle 中有效,但在我的网站中无效

javascript - JS从字符串中读取对象

javascript - 在 Socket.io 基本聊天应用程序中添加聊天机器人

c++ - 如何在 C++ 中实现泛型成员对象?

grails - 从 Groovy 类调用 grails 插件闭包

javascript - 将闭包传递给 Jquery $.each