JavaScript和Node.JS – 无法理解为什么variables在callback中是未定义的

所以我开始学习NodeJS,并创build一个简单的HTTP服务器,如“Node Beginner”中所述。 我有一个Router对象,它包含一个路由table ,它将path名映射到要调用的函数。 这是通过一个关键值对象来实现的。

现在,我的Server对象有一个指向上述对象的router成员。 (对于松耦合,保持路由器和服务器分离),以及start()服务器的start()方法。 如下所示:

 Server.prototype.start = function() { var myRouter = this.router; http.createServer(function(req, res) { var path = url.parse(req.url).pathname; res.write(myRouter.route(path, null)); res.end(); }).listen(80); }; 

现在我创build了一个myRoutervariables,它指向Server对象的router引用,然后在createServer函数中使用它的route()函数执行路由。 此代码工作。 但是,如果我省略创buildmyRoutervariables部分,并直接在createServer执行路由,如下所示:

 res.write(this.router.route(path, null)); 

它说this.router是不确定的。 我知道这与范围有关,因为提供给createServer的函数稍后在接收到请求时执行,但是,我无法理解创buildmyRouter如何解决此问题。 任何帮助将不胜感激。

variablesmyRourer解决了这个问题,因为函数记住了它们被创build的环境( Closure )。 因此callback知道myRoutervariables

你的问题的另一个解决scheme可能是设置callback的这个值到一个特定的对象与绑定方法( 绑定 )。

 http.createServer(function(req, res) { var path = url.parse(req.url).pathname; res.write(this.router.route(path, null)); res.end(); }.bind(this)).listen(80); 
 In the request callback , function(req, res) { var path = url.parse(req.url).pathname; res.write(myRouter.route(path, null)); res.end(); } 'this' doesnot refer to your outer Server. To use this inside this callback use bind. Server.prototype.start = function() { var myRouter = this.router; http.createServer(function(req, res) { var path = url.parse(req.url).pathname; res.write(myRouter.route(path, null)); res.end(); }.bind(this)).listen(80); };