JS函数原型out of context node express

在具有上下文的节点中使用原型时遇到问题。

/** * Constructor. * * @param object opts The options for the api. * @param object config The application's configuration. * @param object db The database handler. * @return void */ var clientModel = function ( opts, config, db ) { this.opts = opts; this.config = config; this.db = db; }; /** * Get a list of items. * * @param function cb Callback function. * @return void */ clientModel.prototype.getList = function( cb ) { this.db.query( "SELECT FROM " + this.db.escape("client"), function ( err, rows, fields ) { if( err.code && err.fatal ) { cb( { message: "SQL error locating client." }); return; } if(! rows.length ) { cb( { message: "Unable to locate client." }); return; } cb( false, rows, fields ); }); }; /** * Default http request for getting a list of items. * * * @param object req The http request. * @param object res The http response. * @return void */ clientModel.prototype.httpGetList = function ( req, res ) { this.getList( function ( err, rows, fields ) { res.end("Got a list"); }); } // - Append model to output. module = module.exports = clientModel; 

基本上节点expression式框架调用httpGetList和“这个”没有getList由于“this”由于上下文expression,是否有任何改善我的代码,以便正确地做到这一点,我猜如果它得到了这个.getList那么this.db也会脱离上下文吗?

任何帮助赞赏。

你可以把你的函数绑定到一个对象上,这样不pipe他们如何被调用, this都会像你期望的那样。 你可以在这里find更多的信息。

你可以在你的构造函数中绑定这些方法。 下划线库有一个有用的bindAll方法来帮助你。

我build议你在模块中创build实例并导出处理请求的函数。

 /** * Exports. * * @param object opts The options for the api. * @param object config The application's configuration. * @param object db The database handler. * @return void */ module = module.exports = function ( opts, config, db ) { var instance = new clientModel( opts, config, db ); return { /** * Default http request for getting a list of items. * * * @param object req The http request. * @param object res The http response. * @return void */ httpGetList : function ( req, res ) { instance.getList( function ( err, rows, fields ) { res.end("Got a list"); }); } }; };