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了一个myRouter
variables,它指向Server
对象的router
引用,然后在createServer
函数中使用它的route()
函数执行路由。 此代码工作。 但是,如果我省略创buildmyRouter
variables部分,并直接在createServer
执行路由,如下所示:
res.write(this.router.route(path, null));
它说this.router
是不确定的。 我知道这与范围有关,因为提供给createServer
的函数稍后在接收到请求时执行,但是,我无法理解创buildmyRouter
如何解决此问题。 任何帮助将不胜感激。
variablesmyRourer
解决了这个问题,因为函数记住了它们被创build的环境( Closure )。 因此callback知道myRouter
variables
你的问题的另一个解决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); };