2014-03-28 48 views
0

我在此處使用Node,並將以下函數用作控制器操作。我使用Mongoose來訪問模型,並且在Game.findById()的範圍內,我無法訪問它上面的任何變量,即this.player和this.gameId。使用Mongoose和Node.js進行JavaScript範圍界定問題

有誰知道我做錯了什麼?請注意,我想訪問console.log()語句所在的變量,但我無法訪問它。 this.player返回undefined。在此先感謝您的幫助。

exports.cleanup = function(req, res) { 
    this.player = req.body; 
    this.gameId = req.url.split('/')[2]; 
    debugger; 
    Game.findById(this.gameId, function(err, game) { 
    if (err) return err; 
    console.log(this.player); 
    }); 
}; 

回答

0

this指的是不同的東西兩個函數裏面,每一個都有自己的範圍和自己的this(儘管this可能在某些情況下是不確定的,看到一對夫婦的參考下圖)。

你會想要的是類似於以下內容 - 注意self變量。

exports.cleanup = function(req, res) { 
    this.player = req.body; 
    this.gameId = req.url.split('/')[2]; 
    var self=this; 
    debugger; 
    Game.findById(this.gameId, function(err, game) { 
    if (err) return err; 
    console.log(self.player); 
    }); 
}; 

這可能是幫助一對夫婦資源的理解this