【问题标题】:JavaScript and Node.JS -- unable to understand why variable in callback is undefined [duplicate]JavaScript 和 Node.JS - 无法理解为什么回调中的变量未定义 [重复]
【发布时间】:2016-06-29 05:56:50
【问题描述】:

所以我开始学习 NodeJS 并创建一个简单的 HTTP 服务器,如 The Node Beginner book 中所述。我有一个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 变量,它指向Server 对象的router 引用,然后在createServer 函数中,使用它的route() 函数执行路由。此代码有效。但是,如果我省略创建myRouter 变量部分并直接在createServer 中执行路由,如下所示:

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

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

【问题讨论】:

标签: javascript node.js scope


【解决方案1】:

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

【讨论】:

    【解决方案2】:
    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);
    };
    

    【讨论】:

    • 是的,但是myRouter 如何正确引用?
    • 您的 myRouter 是在服务器内部声明的,而不是在 createserver callbacl 内部声明的,这就是原因
    • 为什么将整个帖子格式化为代码?
    • 抱歉会处理的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-21
    • 2016-12-26
    • 1970-01-01
    • 2014-12-05
    • 1970-01-01
    • 2013-01-23
    相关资源
    最近更新 更多