This question already has answers here:
How to access the correct `this` inside a callback?
                                
                                    (10个答案)
                                
                        
                                3年前关闭。
            
                    
因此,我开始学习NodeJS并按照The Node Beginner一书中的说明创建一个简单的HTTP服务器。我有一个Router对象,它包含一个路由table,该路径将路径名映射到要调用的函数。这是通过键值对象实现的。

现在,我的Server对象具有一个router成员,该成员指向上述对象。 (对于松散耦合,请保持路由器和服务器分开),并使用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);
};


现在,我创建了一个myRouter变量,该变量指向router对象的Server引用,然后在createServer函数中,使用其route()函数执行路由。此代码有效。但是,如果我忽略创建myRouter变量部分,而直接在createServer中执行路由,如下所示:

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


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

最佳答案

变量myRourer解决了该问题,因为函数会记住创建它们的环境(Closure)。因此,回调知道myRouter变量

解决您问题的另一种方法是使用bind方法(bind)将回调的this值设置为特定对象。

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);

07-25 22:19
查看更多