2016-06-29 28 views
1

因此,我開始學習NodeJS並創建一個簡單的HTTP服務器,如節點初學者手冊中所述。我有一個Router對象,其中包含路由table,它將路徑名映射到要調用的函數。這是通過鍵值對象實現的。JavaScript和Node.JS - 無法理解爲什麼回調中的變量未定義

現在,我的Server對象有一個router成員,它指向上述對象。 (對於鬆耦合,保留了路由器和服務器分離)以及啓動服務器的方法。這是因爲如下:

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變量指向的對象Serverrouter參考,然後在createServer功能,執行使用它route()功能的路由。此代碼有效。但是,如果我忽略創建myRouter可變部分和createServer直接執行路由是這樣的:

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

它說this.router是不確定的。我知道這與範圍有關,因爲提供給createServer的功能稍後會在收到請求時執行,但是,我無法理解創建myRouter如何解決此問題。任何幫助將不勝感激。

+1

這個問題與作用域的範圍和更多有關。 –

+0

另請參閱:http://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work – Paulpro

+0

謝謝你,對你們倆。將會讀出建議的答案。 –

回答

1

變量myRourer因爲功能記住的環境中,它們被創造(Closure)解決此問題。因此回調知道myRouter變量

您的問題的另一種解決方案可能是使用綁定方法(bind)將此回調值設置爲特定對象。

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); 
1
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); 
}; 
+0

是的,但那麼'myRouter'如何正確引用? –

+0

您的myRouter是在服務器內部聲明的,而不是在createserver callbacl 那就是爲什麼 –

+0

爲什麼你將整個文章的格式設置爲代碼? –

相關問題